In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will show you how to pull the cache through Springboot and @ Cacheable annotations and how to clear the cache through @ CacheEvict. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.
There are different ways to use caching in projects. Today, we will complete the operation of pulling the cache through the @ Cacheable annotation. First of all, the data type generated by the @ Cacheable annotation is of type key-value; only one more will be generated.
Project demo download
The code shows the start maven configuration org.springframework.boot spring-boot-starter-redis 1.4.3.RELEASE2.application.properties file that 1.pox.xml introduced into redis
Configure the contents of the default redis configuration items for springboot; the test uses a stand-alone environment
Spring.redis.database=0 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=khanyu spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.timeout=50003.RedisCacheableConfig cache configuration class content First of all, the default key and value serialization methods of redis are not easy to show in the tool class, so use custom serialization methods to handle key and value values FastjsonRedisSerializer is a custom serialization method class, RedisConnectionFactory via fastJson is springboot by default @ Beanpublic RedisTemplate redisTemplate (@ Autowired RedisConnectionFactory factory) {StringRedisTemplate template = new StringRedisTemplate (factory); template.setKeySerializer (new StringRedisSerializer ()) / / set the serialization / deserialization mode of key cached in redis template.setValueSerializer (new FastjsonRedisSerializer ()); / / set the serialization / deserialization mode of value in redis template.afterPropertiesSet (); return template } what is configured here is that RedisCacheManager implements the cacheManager attribute of @ Cacheable annotation content to specify whether the cache is in redis or in our local memory. What is configured here is the cache time of each key value in Map in the configuration in redis, and then the default key configuration time @ Bean ("redisCacheManager") @ Primarypublic RedisCacheManager initRedisCacheManager (@ Autowired RedisTemplate redisTemplate) {RedisCacheManager redisCacheManager = new RedisCacheManager (redisTemplate) Map expires = new HashMap (); expires.put ("user", 1000L); / / set the cache time expires.put of the specified key in redis ("khy", 1000L); / / set the cache time of the specified key in redis / /. Each key can set redisCacheManager.setExpires (expires); redisCacheManager.setDefaultExpiration (1500); / / set the default key cache expiration time return redisCacheManager here. } configure default local cache content configuration / * set FactoryBean * @ author khy * @ createTime to be cached locally at 3:43:47 * @ return * / @ Beanpublic ConcurrentMapCacheFactoryBean initConcurrentMapCacheFactoryBean () {ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean (); cacheFactoryBean.setName ("khy"); return cacheFactoryBean } / * @ Cacheable annotation cacheManager specifies whether the corresponding manager type is local or dependent on Redis * @ author khy * @ createTime 3:46:21, November 18, 2020 * @ param concurrentMapCache * @ return * / @ Bean ("simpleCacheManager") public SimpleCacheManager initLocalCacheManager (@ Autowired ConcurrentMapCache concurrentMapCache) {SimpleCacheManager simpleCacheManager = new SimpleCacheManager (); List caches = new ArrayList () {{add (concurrentMapCache);}} SimpleCacheManager.setCaches (caches); return simpleCacheManager;} configures a custom cache key generation method; / * this is how the prefix is set * the following code will be used; * @ author khy * @ createTime 10:20:02 on October 22nd, 2020 * @ return * / @ Bean ("prefixKeyGenerator") public PrefixKeyGenerator initPrefixKeyGenerator () {PrefixKeyGenerator prefixKeyGenerator = new PrefixKeyGenerator ("prefix"); return prefixKeyGenerator } the generator of custom cache key public class PrefixKeyGenerator extends SimpleKeyGenerator {private static final String SLOT_CHANGER = "{Qi}"; private static final String COLON = ":"; private String module;public PrefixKeyGenerator (String module) {this.module = module } / * Custom prefix settings (by converting the passed object to key and then stitching) * * ToStringStyle.SHORT_PREFIX_STYLE * this is a toString style without classful prefixes. The output with ToStringBuilder class using User instance is * / public Object generate (Object target, Method method, Object...). Params) {StringBuilder key = new StringBuilder (); Object result = super.generate (target, method, params); if (result instanceof String & & JedisClusterCRC16.getSlot ((String) result) = = 0) {result = result + "{Qi}";} / is the prefix: method class class. Method name: result// if the same class with the same name appears under different packages, you need to get target.getClass (). GetName (); full-path class name key.append (this.module) .append (":") .append (target.getClass (). GetSimpleName ()) .append (".") .append (method.getName ()) .append (":") .append (result); return key.toString () }} 4.CacheableController sets the cache to redis by requesting local code, http://localhost:8080/cacheable/getSimpleString1?userName=candyhttp://localhost:8080/cacheable/getSimpleString1?userName=candy2 figure 1. In the tool, we can see that the cache value is cached according to the value of our request parameter. Request the following link again because the cache effect is the same, so it will not enter the method http://localhost:8080/cacheable/getSimpleString2?userName=candyhttp://localhost:8080/cacheable/getSimpleString2?userName=candy2 figure 2. Calling the following method caches http://localhost:8080/cacheable/getSimpleString3?userName=candy2 in two zset
/ * * the simplest cache setting method * request to specify parameter content Then cache the result of the response to the redis cache * the current cache sets two cache formats * one is the value of userName in the request parameters of String type value is the response result * the other is the zset format key = khy~keys row is the value of userName * * at the same time, because the specified value is khy in the RedisCacheManager configuration of khy in RedisCacheableConfig, the cache survival time is 1000s * so the valid time of both caches is 1000 * * the content in the method will be printed when the http://localhost:8080/cacheable/getSimpleString1?userName=candy is requested for the first time, but at the time of the request, it will be obtained directly from the cache because the userName=candy parameter is unchanged. Do not enter the method * although requested many times, the validity time of the cached candy of the corresponding String type will not be updated * * the later request http://localhost:8080/cacheable/getSimpleString1?userName=candy1 * will add a new entry to the cache colleague update khy~keys of the newly inserted String type * @ author khy * @ createTime 10:28:23 * @ param userName * @ return * / @ RequestMapping ("/ getSimpleString1") @ Cacheable (cacheManager= "redisCacheManager", value= "khy") public String getSimpleString1 (String userName) {System.out.println ("getSimpleString entered method executed" + userName); userName= "+ userName;} / * * returned by return" is consistent with the result returned by getSimpleString1 * @ author khy * @ createTime 10:52:31 * @ param userName * @ return * / @ RequestMapping ("/ getSimpleString2") @ Cacheable (cacheManager= "redisCacheManager", value= "khy", key= "# userName") public String getSimpleString2 (String userName) {System.out.println ("getSimpleString2 enters method executed" + userName); the cache returned by return "userName=" + userName;} / * String is consistent with the result returned by getSimpleString1. * but because value specifies two So the zset * in generation 2 is khy~keys and 111~keys * because the default time for RedisCacheManager configuration in RedisCacheableConfig is 1500 seconds * @ author khy * @ createTime 11:00:53 on October 22nd, 2020 * @ param userName * @ return * / @ RequestMapping ("/ getSimpleString3") @ Cacheable (cacheManager= "redisCacheManager", value= {"khy") ) public String getSimpleString3 (String userName) {System.out.println ("getSimpleString3 entered method executed" + userName) Return "returned userName=" + userName;} 2. Cached key with multiple request parameters uses expressions to obtain values in request parameters as key to implement cached http://localhost:8080/cacheable/getSimpleString5?userName=candy&userId=111http://localhost:8080/cacheable/getSimpleString5?userName=candy&userId=1112. If an object is used to accept parameters directly, an attribute in the object is obtained as key http://localhost:8080/cacheable/getSimpleEntity4?userName=candy&password=1112 through an expression.
/ * * although multiple request parameters are passed, the # userName specified in key as the key value * is mainly based on the value of userName. Although the later userId parameter is modified, it will not enter the current method * @ author khy * @ param userName * @ return * / @ RequestMapping ("/ getSimpleString4") @ Cacheable (cacheManager= "redisCacheManager", value= "khy") at 11:39:03 on October 22nd, 2020. Key= "# userName") public String getSimpleString4 (Integer userId,String userName) {System.out.println ("getSimpleString4 entered method executed" + userName+userId) The difference between the userName= returned by return + userName;} / * * and getSimpleString4 is that the parameters are superimposed together. * the key formed is based on the decision of both userId_userName and * @ author khy * @ createTime. 1:36:35 on October 22nd, 2020 * @ param userId * @ param userName * @ return * / @ RequestMapping ("/ getSimpleString5") @ Cacheable (cacheManager= "redisCacheManager", value= "khy", key= "# userId+'_'+#userName") public String getSimpleString5 (Integer userId,String userName) {System.out.println ("getSimpleString5 entry method executed" + userName+userId) Return "returned userName=" + userName } / * this is a combination of userName and password in the request parameters as key * @ author khy * @ createTime in redis * @ param userEntity * @ return * / @ RequestMapping ("/ getSimpleEntity4") @ Cacheable (cacheManager= "redisCacheManager", value= "user", key= "# userEntity.userName+'_'+#userEntity.password") public UserEntity getSimpleEntity4 (UserEntity userEntity) {UserEntity cacheEntity = new UserEntity () CacheEntity.setId (1); cacheEntity.setAge (10); cacheEntity.setUserName ("well-off"); cacheEntity.setPassword ("password123"); cacheEntity.setCreateTime (new Date ()); System.out.println ("getSimpleEntity4 entry method content"); return cacheEntity } 5.PrefixKeyController requests with custom key request the key content http://localhost:8080/prefixKey/getSimpleString1?userName=candy http://localhost:8080/prefixKey/getSimpleString1?userName=candy1 set in redis by requesting the following link
The type of generated key below this is in the custom prefix generator
/ * set the corresponding prefix content through prefixKeyGenerator; * set the key prefix content in the corresponding cache through our custom prefix class * http://localhost:8080/prefixKey/getSimpleString1?userName=candy * then set the key in the corresponding cache as * prefix:PrefixKeyController.getSimpleString1:candy * @ author khy * @ createTime 10:02:01 on November 3, 2020 * @ param userName * @ return * / @ RequestMapping ("/ getSimpleString1") @ Cacheable (cacheManager= "redisCacheManager", value= "khy") KeyGenerator= "prefixKeyGenerator") public String getSimpleString1 (String userName) {System.out.println ("getSimpleString entered method executed" + userName) Return "returned userName=" + userName;} @ RequestMapping ("/ getSimpleString1") @ Cacheable (cacheManager= "redisCacheManager", value= "khy", keyGenerator= "prefixKeyGenerator") public String getSimpleString1 (String userName) {System.out.println ("getSimpleString entered method executed" + userName); return "returned userName=" + userName } / * with multiple parameters to splice key through prefixKeyGenerator * request http://localhost:8080/prefixKey/getSimpleString2?userName=candy&password=123 * cache set by redis prefix:PrefixKeyController.getSimpleString2:SimpleKey [candy,123] * * request http://localhost:8080/prefixKey/getSimpleString2 * cache prefix:PrefixKeyController.getSimpleString2:SimpleKey set by redis [null Null] * * request the cache prefix:PrefixKeyController.getSimpleString2:SimpleKey [candy,null] * @ author khy * @ createTime set by http://localhost:8080/prefixKey/getSimpleString2?userName=candy * redis at 10:17:58 on November 3, 2020 * @ param userName * @ param password * @ return * / @ RequestMapping ("/ getSimpleString2") @ Cacheable (cacheManager= "redisCacheManager", value= "khy", keyGenerator= "prefixKeyGenerator") public String getSimpleString2 (String userName String password) {System.out.println ("getSimpleString2 entry method executed" + userName+ "password=" + password) Return "userName=" + userName;} if the request parameter is an object, then toString () needs to rewrite the method parameter object / * the request parameter is the specified object content; * but if the UserEntity is not processed, the generated key is with * prefix:PrefixKeyController.getSimpleEntity:com.khy.entity.UserEntity@e1475c6 * memory address In this way, every request is not the same one, but there is a problem that the object's toString () method needs to be rewritten * return ToStringBuilder.reflectionToString (this, ToStringStyle.SHORT_PREFIX_STYLE). * * request http://localhost:8080/prefixKey/getSimpleEntity * prefix:PrefixKeyController.getSimpleEntity:UserEntity [userName=,password=,id=,age=,createTime=] * * request is http://localhost:8080/prefixKey/getSimpleEntity?userName=candy&password=123 * prefix:PrefixKeyController.getSimpleEntity:UserEntity [userName=candy,password=123,id=,age= CreateTime=] * @ author khy * @ createTime 10:25:46 * @ param userEntity * @ return * / @ RequestMapping ("/ getSimpleEntity") @ Cacheable (cacheManager= "redisCacheManager", value= "khy", keyGenerator= "prefixKeyGenerator") public UserEntity getSimpleEntity (UserEntity userEntity) {UserEntity cacheEntity = new UserEntity () CacheEntity.setId (1); cacheEntity.setAge (10); cacheEntity.setUserName ("well-off"); cacheEntity.setPassword ("password123"); cacheEntity.setCreateTime (new Date ()); System.out.println ("getSimpleEntity entry method content"); return cacheEntity } public class UserEntity implements Serializable {@ Overridepublic String toString () {try {return ToStringBuilder.reflectionToString (this, ToStringStyle.SHORT_PREFIX_STYLE);} catch (Exception var2) {var2.printStackTrace (); return super.toString () } 6.@CachePut updates the current return value to the cache regardless of whether there is a value in the cache or not / * * @ CachePut Note is that the current method is executed regardless of whether there is a value in the cache or not, and the result is returned to the cache * every time the request accesses the http://localhost:8080/prefixKey/getSimpleEntity2?userName=candy&password=123 * the following method is executed regardless of whether the cache contains key or not And set the returned value to update to the cache * prefix:PrefixKeyController.getSimpleEntity2:UserEntity [userName=candy] Password=123,id=,age=,createTime=] * @ author khy * @ createTime 10:54:22 * @ param userEntity * @ return * / @ RequestMapping ("/ getSimpleEntity2") @ CachePut (cacheManager= "redisCacheManager", value= "khy", keyGenerator= "prefixKeyGenerator") public UserEntity getSimpleEntity2 (UserEntity userEntity) {UserEntity cacheEntity = new UserEntity () CacheEntity.setId (1); cacheEntity.setAge (10); cacheEntity.setUserName ("well-off"); cacheEntity.setPassword ("password123"); cacheEntity.setCreateTime (new Date ()); System.out.println ("getSimpleEntity2 entry method content"); return cacheEntity } the principle that 7.@CacheEvict executes the current method to empty all the key values in the specified cache is mainly based on the value in the annotation attribute; it is mainly observed that we will generate a cache of zset structure in the cache after we specify value in the @ Cacheable annotation, and there will be an extra pair of key-value cache values whenever the method request parameters are different, and the corresponding key will also be cached in the zset So the principle of emptying the cache is to get all the key to clear the cache from zset and then clear the zset cache / * clear the data in the cache is mainly related to the value value, that is, the @ Cacheable annotation that the value attribute is set to khy * generates all the key in a record in zset format in the cache. Then the cleanup time is deleted according to all the elements of the element * in the zset, that is, regardless of whether the method userName is passed by the above method or not, the value in the method can be emptied * multiple key * @ author khy * @ createTime can be specified at 10:34:21 on November 18, 2020 * @ param userName * @ return * / @ RequestMapping ("/ clearSimple") @ CacheEvict (cacheManager= "redisCacheManager", value= "khy"). AllEntries=true) public UserEntity clearSimple (String userName) {UserEntity cacheEntity = new UserEntity () CacheEntity.setId (1); cacheEntity.setAge (10); cacheEntity.setUserName ("well-off"); cacheEntity.setPassword ("password123"); cacheEntity.setCreateTime (new Date ()); System.out.println ("clear cache function method executed"); return cacheEntity;}
The above is the use of @ Cacheable and related annotations; in fact, except that it is more convenient; caching is not used in general projects; it will be generated by the same tool class, and it is all generated according to the data structure we specify. Not all of this is treated as key-value.
This is how the editor shares the principle of how to pull the cache through Springboot and @ Cacheable annotations and clear the cache through @ CacheEvict. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are 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.
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.