Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem that the key value set by @ CachePut cannot match the value of @ CacheValue

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to solve the problem that the key value of @ CachePut setting can not match the value of @ CacheValue. It is very detailed and has certain reference value. Interested friends must finish reading it!

The key value set by @ CachePut cannot match the value of @ CacheValue. The basic data type of cache annotation key must be unified / / based on the value of the id query cache @ Cacheable (value = "testCache") public TestEntity listById (int id) {return testMapper.listById (id);} / modify the value of the cache @ CachePut (value = "testCache", key = "# result.id") public TestEntity updateById (TestEntity testEntity) {System.out.println ("run result:" + testMapper.updateById (testEntity)) System.out.println ("id:" + testEntity.getId ()); return testEntity;} / / before entity class modification public class TestEntity {private String id;// Note here private String name; private String sex;} / / entity class modification public class TestEntity {private int id; private String name; private String sex;}

Now that the modification is complete, it can be concluded that the basic data types of key must be unified.

In cache, the data type is very strict, and the same id is different from the String type.

At first, I was perplexed by this error for a long time, because in the results returned by mybatis, there was no error for int and String type id. At the beginning, the breakpoint and the source code found that there was no change to the generation of this key. The result.id I wrote had been passed to the place where the id was generated, although it was not very clear how to generate it.

Until today, when I tested it again and again, I wrote "result." It suddenly dawned on me when I found out that id is a String type.

Considerations for Spring-Cache key setup

In order to improve the concurrency performance of the project, local memory Cache is introduced to cache the processing results of three types of functions: external data source access, Restful API calls and reusable complex calculations. Currently, Spring Cache's @ Cacheable annotation is used, and Guava Cache is selected for cache implementation.

The configuration of the cache will not be described here, but the configuration of key will be explained:

1. Basic form @ Cacheable (value= "cacheName", key "# id") public ResultDTO method (int id); 2. Combination form @ Cacheable (value= "cacheName", key "T (String) .valueof (# name) .concat ('-'). Concat (# password)) public ResultDTO method (int name, String password); 3. Object form @ Cacheable (value=" cacheName ", key" # user.id) public ResultDTO method (User user). 4. Custom Key generator @ Cacheable (value= "gomeo2oCache", keyGenerator = "keyGenerator") public ResultDTO method (User user)

There is one particular pit to note: Spring's default SimpleKeyGenerator does not combine function names into key.

Take a chestnut.

@ Component public class CacheTestImpl implements CacheTest {@ Cacheable ("databaseCache") public Long test1 () {return 1L;} @ Cacheable ("databaseCache") public Long test2 () {return 2L;} @ Cacheable ("databaseCache") public Long test3 () {return 3L;} @ Cacheable ("databaseCache") public String test4 () {return "4" }}

Our expected output is:

one

two

three

four

The actual output is:

one

one

one

ClassCastException: java.lang.Long cannot be cast to java.lang.String

In addition, an array of atomic types, which is directly used as a key, will not take effect.

To solve the above two problems, a custom KeyGenerator is defined as follows:

Class CacheKeyGenerator implements KeyGenerator {/ / custom cache key public static final int NO_PARAM_KEY = 0; public static final int NULL_PARAM_KEY = 53; @ Override public Object generate (Object target, Method method, Object... Params) {StringBuilder key = new StringBuilder (); key.append (target.getClass (). GetSimpleName ()) .append (".") .append (method.getName ()) .append (":"); if (params.length = = 0) {return key.append (NO_PARAM_KEY) .append () } for (Object param: params) {if (param = = null) {log.warn ("input null param for Spring cache, use default key= {}", NULL_PARAM_KEY); key.append (NULL_PARAM_KEY);} else if (ClassUtils.isPrimitiveArray (param.getClass () {int length = Array.getLength (param) For (int I = 0; I < length; iTunes +) {key.append (Array.get (param, I)); key.append (',');}} else if (ClassUtils.isPrimitiveOrWrapper (param.getClass ()) | | param instanceof String) {key.append (param) } else {log.warn ("Using an object as a cache key may lead to unexpected results. "+" Either use @ Cacheable (key=..) Or implement CacheKey. Method is "+ target.getClass () +" # "+ method.getName (); key.append (param.hashCode ());} key.append ('-');} String finalKey = key.toString (); long cacheKeyHash = Hashing.murmur3_128 (). HashString (finalKey, Charset.defaultCharset ()). AsLong () Log.debug ("using cache key= {} hashCode= {}", finalKey, cacheKeyHash); return key.toString ();}

By using this method, the problems such as multi-parameter, atomic type array and method name recognition can be solved.

The above is all the contents of this article entitled "how to solve the problem that the key value set by @ CachePut does not match the value of @ CacheValue". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report