In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use Spring Cache to set cache condition operations. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Principle of setting cache condition by Spring Cache
Starting with Spring3.1, the Spring framework provides support for Cache and provides an abstraction for cache usage. By adding a small amount of various annotation it defines to existing code, the caching method can return objects.
The main annotations provided are @ Cacheable, @ CachePut, @ CacheEvict and @ Caching, as shown in the following table:
The annotation @ Cacheable can be annotated on a class or method: the annotation on the method indicates that the method supports data caching; the annotation on the class indicates that all methods of the class support data caching. Specific function: before executing the method body, check whether there is a cache with the same key value in the cache, if there is a corresponding cache, directly return the value in the cache; if there is no corresponding cache, execute the corresponding method body to obtain data, and store the data in the cache. @ CachePut can be annotated on a class or method to indicate that data caching is supported. Specific function: does not check whether there is a corresponding cache in the cache before the method execution, but executes the method body every time, and stores the method execution result in the cache. If the cache of the corresponding key value exists, update the value value corresponding to key. @ CacheEvict can be annotated on a class or method to clear the cache of the corresponding key value. @ Caching can be annotated on a class or method. It has three properties, cacheable, put, and evict, to specify @ Cacheable, @ CachePut, and @ CacheEvict, respectively.
When you need to use multiple annotations on a class or method at the same time, you can use @ Caching, such as:
@ Caching (cacheable=@Cacheable ("User"), evict = {@ CacheEvict ("Member"), @ CacheEvict (value = "Customer", allEntries = true)}) @ Cacheable
As shown in the following table:
The @ Cacheable attribute indicates that key represents the name of the cache, which must be specified and must have at least one value, such as @ Cacheable (value= "Dept") or @ Cacheable (value= {"Dept", "Depts"}) condition indicates whether the cache is required. The default is empty, which means that all cases will be cached. Specified by SpEL expression, it will be cached if the value of condition is true and not if it is false, such as @ Cacheable (value= "Dept", key= "'deptno_'+# deptno", condition= "# deptno3") public String getLocByDname (@ RequestParam ("dname") String dname) {/ / key dynamic parameter QueryWrapper queryMapper = new QueryWrapper (); queryMapper.eq ("dname", dname); Dept dept = deptService.getOne (queryMapper); return dept.getLoc ();}
Example: unless, that is, caching when the condition is not valid
# result represents the return value, which means that it is not cached when the return code is not equal to 200, that is, it is equal to 200.
@ ResponseBody@GetMapping ("/ getDeptByDname") @ Cacheable (cacheNames = "dept", key = "# dname", unless = "# result.code! = 200") public Result getDeptByDname (@ RequestParam (" dname ") String dname) {/ / key dynamic parameter QueryWrapper queryMapper = new QueryWrapper (); queryMapper.eq (" dname ", dname); Dept dept = deptService.getOne (queryMapper); if (dept = = null) return ResultUtil.error Else return ResultUtil.success (dept);} Cache cache configuration 1, pom.xml org.springframework.boot spring-boot-starter-cache org.springframework.boot spring-boot-starter-aop org.reflections reflections 0.9.112, Ehcache configuration file 3, configuration class @ Configuration@EnableCachingpublic class CustomConfiguration {/ * * @ see org.springframework.cache.interceptor.SimpleKeyGenerator * Generate a key based on the specified parameters. * / public static Object generateKey (Object... Params) {if (params.length = = 0) {return SimpleKey.EMPTY;} if (params.length = = 1) {Object param = params [0]; if (param! = null & &! param.getClass (). IsArray ()) {return param;}} return new SimpleKey (params) } / * if target is used as part of key, CGLIB dynamic proxy may cause duplicate caching * Note: the returned key must override hashCode () and toString () Prevent cache misses caused by inconsistent key objects * for example: ehcache underlying storage net.sf.ehcache.store.chm.SelectableConcurrentHashMap#containsKey * / @ Bean public KeyGenerator customKeyGenerator () {return (target, method, params)-> {final Object key = generateKey (params) StringBuffer buffer = new StringBuffer (); buffer.append (method.getName ()); buffer.append ("::"); buffer.append (key.toString ()); / / be sure to convert to String, otherwise the ehcache key object may be different and the cache cannot hit return buffer.toString ();} } / * redis cache manager * / @ Bean @ ConditionalOnBean (RedisConfiguration.class) @ ConditionalOnProperty (prefix = "spring.cache", name = "type", havingValue = "redis" MatchIfMissing = false) public CacheManager redisCacheManager (RedisConnectionFactory redisConnectionFactory) {RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig () .serial izeKeysWith (RedisSerializationContext.SerializationPair.fromSerializer (new StringRedisSerializer () .serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (new GenericJackson2JsonRedisSerializer () .entryTtl (Duration.ofMinutes (10)) Return RedisCacheManager .builder (RedisCacheWriter.lockingRedisCacheWriter (redisConnectionFactory)) .cacheDefaults (config) .build () } / * ehcache cache manager (default) * default XML files {@ link net.sf.ehcache.config.ConfigurationFactory#parseConfiguration ()} * / @ Bean @ ConditionalOnProperty (prefix = "spring.cache", name = "type", havingValue = "ehcache", matchIfMissing = true) public CacheManager ehcacheCacheManager () {net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.create () / * package scan to find the specified annotation and add cacheNames to net.sf.ehcache.CacheManager (singleton) * / Reflections reflections = new Reflections ("com.example.demo.service", new TypeAnnotationsScanner (), new SubTypesScanner (), new MethodAnnotationsScanner ()); Set
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.