In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to solve the pit in springCache configuration". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The pit in the springCache configuration
The project is based on SpringBoot and uses SpringCache.
Earlier, I found a SpringCache configuration on the Internet, but later, due to the need to use a custom serialization method, I injected a custom serialization class. But later found that the custom serialization class was never called, and later looked at the source code and finally found the reason.
Attach the correct configuration @ Bean public CacheManager cacheManager (RedisConnectionFactory factory, SessionSerializer serializer) {logger.debug ("generate cache manager"); logger.debug ("injected serialization tool = {}", serializer); RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair.fromSerializer (serializer); logger.debug ("generated cache serialization tool = {}", pair); RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig () / / generate a default configuration to customize the cache through the config object config = config.entryTtl (Duration.ofMinutes (10)) / / set the default expiration time of the cache, and also use Duration to set .serializeValuesWith (pair) / / .serializeKeysWith (RedisSerializationContext.SerializationPair.fromSerializer (new StringRedisSerializer () .serialCachingNullValues () / do not cache null logger.debug ("initialized config= {}", config); / / set an initialized cache space set collection Set cacheNames = new HashSet (); cacheNames.add (CACHE_NAME) Return RedisCacheManager.builder (new CusTtlRedisCacheWriter (factory)) / / initializing a cacheManager .cacheDefaults (config) / / with a custom cache configuration must be executed first, otherwise the actual runtime is defaultConfig .initialCacheNames (cacheNames) / / withInitialCacheConfigurations (configMap) / / .transactionAware () .build () }
The important thing is that in the last line of return, the information found earlier said that the initialCacheNames method must be implemented first, otherwise it would be Barabara, and it would fall into the pit.
If the initialCacheNames method is executed first, DefaultConfig is actually used in CacheManager, and the serialization method in it is Jdk serialization, and it is useless to call cacheDefaults later.
So, the cacheDetaults method must be executed first.
SpringCache configuration and some problem solving configuration
1. ApplicationContext.xml
Spring is stored in ConcurrentHashMap by default, and the activityCache awardsCache in the configuration is the name of a ConcurrentHashMap object. Spring also supports the use of EHCache to store caches.
two。 Add @ Cacheable to the implementation class of service
/ / @ Service//public class LotteryActivityServiceImpl implements LotteryActivityService@Cacheable (value = "activityCache", key = "# shortName") public LotteryActivity findByShortName (String shortName) {log.info ("query activity: {} from database.", shortName); return activityRepository.findByShortName (shortName) } @ Cacheable parameter value cache name, defined in the spring configuration file, must specify at least one such as: @ Cacheable (value= "mycache") or @ Cacheable (value= {"cache1", "cache2"} key cache key, which can be empty. If you specify to write according to the SpEL expression, if not specified, the default combination is based on all the parameters of the method, such as @ Cacheable (value= "testcache", key= "# userName") condition cache condition. Can be empty, written in SpEL, return true or false, and cache only for true for example: @ Cacheable (value= "testcache", condition= "# userName.length () > 2")
Add @ CacheEvict to the method that needs to clear the cache
CacheEvict (value= "activityCache", allEntries = true, beforeInvocation = true) public void cleanActivityCache (String shortName) {log.info ("cleaned cache activity: {}", shortName) } @ CacheEvict parameter value cache name, defined in the spring configuration file, must specify at least one such as: @ CachEvict (value= "mycache") or @ CachEvict (value= {"cache1", "cache2"} key cache key, which can be empty. If you specify to write according to the SpEL expression, if not specified, the default combination is based on all the parameters of the method, such as @ CachEvict (value= "testcache", key= "# userName" condition cache condition). Can be empty, written in SpEL, return true or false, and clear the cache only for true. For example: @ CachEvict (value= "testcache", condition= "# userName.length () > 2") whether allEntries clears all cache contents. Default is false. If specified as true, all caches will be cleared immediately after the method call. For example: @ CachEvict (value= "testcache", allEntries=true) beforeInvocation is empty before method execution, default is false, if specified as true. The cache is cleared before the method is executed. By default, if the method executes and throws an exception, the cache is not emptied for example: @ CachEvict (value= "testcache", beforeInvocation=true)
When you need to ensure that the method is called and you want the result to be cached, you can use @ CachePut
@ CachePut (value= "accountCache", key= "# account.getName ()") / / Update accountCache cache public Account updateAccount (Account account) {return updateDB (account) } @ CachePut parameter value cache name, defined in the spring configuration file, must specify at least one such as: @ Cacheable (value= "mycache") or @ Cacheable (value= {"cache1", "cache2"} key cache key, which can be empty, if you specify to write according to SpEL expressions, if you do not specify The default combination is based on all the parameters of the method, for example: @ Cacheable (value= "testcache", key= "# userName") condition cache condition, which can be empty, written in SpEL, return true or false, and cache only for true. For example: @ Cacheable (value= "testcache", condition= "# userName.length () > 2")
Annotations are best added to methods that implement classes rather than interfaces
Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @ Cache* annotation, as opposed to annotating interfaces. You certainly can place the @ Cache* annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class= "true") or the weaving-based aspect (mode= "aspectj"), then the caching settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a caching proxy, which would be decidedly bad.
A method with @ Cache* annotation cannot be defined in the class that calls the method. For example, if UserController calls findUserByName (String name), and the method has @ Cacheabele annotation, the method cannot be defined in UserController.
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual caching at runtime even if the invoked method is marked with @ Cacheable-considering using the aspectj mode in this case.
The @ Cache* annotation should be added to the public method
When using proxies, you should apply the @ Cache* annotations only to methods with public visibility. If you do annotate protected, private or package-visible methods with these annotations, no error is raised, but the annotated method does not exhibit the configured caching settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods as it changes the bytecode itself.
This is the end of the content of "how to solve the pit in springCache configuration". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.