In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What is the redis@Cacheable annotation and how to set the expiration time? for this question, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Principle explanation
Friendly link handwritten redis @ Cacheable annotation parameter java object as key value
@ Cacheable annotation to store the return value with the annotated method in the redis
Use the method to use @ Cacheable on the method (key = "Test + # P0 + P1marker.")
Indicates that the key value is the test + the first parameter of the method + the second parameter of the method, and the value is the return value of the method.
The following source code indicates the list of people to be acquired. The key value stored in Redis is' Leader'+ leaderGroupId + UUID + yearDetailId
@ Override @ Cacheable (key= "'leader'+#p0+#p1+#p2", value= "leader") public List listLeaders (String leaderGroupId, String uuid, String yearDetailId) {return sysIndexMapper.listLeaders (leaderGroupId, uuid, yearDetailId);}
Equivalent to
@ Override public List listLeaders (String leaderGroupId, String uuid, String yearDetailId) {String key = "leader" + leaderGroupId + uuid + yearDetailId; / / determine whether the cache exists in redis boolean hasKey = redisUtil.hasKey (key) If (hasKey) {/ / if there is a value in the returned redis Object leadersList = redisUtil.get (key); return (List) leadersList;} else {List leadersQuotaDetailList = sysIndexMapper.listLeaders (leaderGroupId, uuid, yearDetailId) / / store the query results in redis redisUtil.set (key, leadersQuotaDetailList); return leadersQuotaDetailList;}}
To put it bluntly, it is in the Redis to determine whether the key value exists in the original method, take the value in memory if it exists, query the database if it does not exist, and store the query results in Redis.
Realization method
Using proxy mode, other handlers can be added before and after method execution. SpringAOP + annotations are used in this paper.
Integrate redis and encapsulate Redis tool class
The expiration time setting is not supported in the original version. This article will implement
source code
Cache configuration class RedisConfig
Package com.huajie.config; import org.springframework.beans.factory.annotation.Value;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.cache.interceptor.KeyGenerator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate Import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper; / * Redis cache configuration class * / @ Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport {@ Value ("${spring.redis.host}") private String host @ Value ("${spring.redis.port}") private int port; @ Value ("${spring.redis.timeout}") private int timeout / / Custom cache key generation strategy @ Bean public KeyGenerator keyGenerator () {return new KeyGenerator () {@ Override public Object generate (Object target, java.lang.reflect.Method method, Object...) Params) {StringBuffer sb = new StringBuffer (); sb.append (target.getClass (). GetName ()); sb.append (method.getName ()) For (Object obj: params) {sb.append (obj.toString ());} return sb.toString ();}} } / / Cache Manager @ Bean public CacheManager cacheManager (@ SuppressWarnings ("rawtypes") RedisTemplate redisTemplate) {RedisCacheManager cacheManager = new RedisCacheManager (redisTemplate); / / set cache expiration time cacheManager.setDefaultExpiration (10000); return cacheManager } @ Bean public RedisTemplate redisTemplate (RedisConnectionFactory factory) {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper (); om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY) Om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper (om); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer (); / / key uses the serialization method of String template.setKeySerializer (stringRedisSerializer); / / key of hash also uses the serialization method of String template.setHashKeySerializer (stringRedisSerializer) / / jackson template.setValueSerializer (jackson2JsonRedisSerializer) is used for value serialization; / / jackson template.setHashValueSerializer (jackson2JsonRedisSerializer) is used for value serialization of hash; template.afterPropertiesSet (); return template } private void setSerializer (StringRedisTemplate template) {@ SuppressWarnings ({"rawtypes", "unchecked"}) Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper (); om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL) Jackson2JsonRedisSerializer.setObjectMapper (om); template.setValueSerializer (jackson2JsonRedisSerializer);}}
Redis dependency introduction, configuration files, tool class RedisUtil, online several versions are similar, this article refers to the following version of the portal
Https://www.yisu.com/article/233562.htm
After the preparation is done, formally write the annotation @ Cacheable nextkey () for secondary caching, which will not be used in this article.
NextKey usage details > Design pattern (practical)-chain of responsibility pattern [] argClass = ((MethodSignature) joinPoint.getSignature ()). GetParameterTypes (); Object [] args = joinPoint.getArgs (); String key = ""; int expireTime = 1800 Try {/ / access method object Method method = className.getMethod (methodName, argClass); method.setAccessible (true) / / determine whether there is @ ExtCacheable annotation if (method.isAnnotationPresent (ExtCacheable.class)) {ExtCacheable annotation = method.getAnnotation (ExtCacheable.class); key = getRedisKey (args,annotation); expireTime = getExpireTime (annotation) }} catch (Exception e) {throw new RuntimeException ("redis cache comment parameter exception", e);} / / get whether the cache exists boolean hasKey = redisUtil.hasKey (key) If (hasKey) {return redisUtil.get (key);} else {/ / execute the original method (java reflection executes method to get the result) Object res = joinPoint.proceed () / / set cache redisUtil.set (key, res); / / set expiration time redisUtil.expire (key, expireTime); return res }} private int getExpireTime (ExtCacheable annotation) {return annotation.expireTime ();} private String getRedisKey (Object [] args,ExtCacheable annotation) {String primalKey = annotation.key (); / / get # p0. Set List keyList = getKeyParsList (primalKey); for (String keyName: keyList) {int keyIndex = Integer.parseInt (keyName.toLowerCase (). Replace ("# p", ")); Object parValue = args [keyIndex]; primalKey = primalKey.replace (keyName, String.valueOf (parValue)) } return primalKey.replace ("+", ") .replace ("'",");} / / get the parameter name private static List getKeyParsList (String key) {List ListPar = new ArrayList () in # p0 in key If (key.indexOf ("#") > = 0) {int plusIndex = key.substring (key.indexOf ("#")) .indexOf ("+"); int indexNext = 0; String parName = ""; int indexPre = key.indexOf ("#") If (plusIndex > 0) {indexNext = key.indexOf ("#") + key.substring (key.indexOf ("#")). IndexOf ("+"); parName = key.substring (indexPre, indexNext);} else {parName = key.substring (indexPre) } ListPar.add (parName.trim ()); key = key.substring (indexNext + 1); if (key.indexOf ("#") > = 0) {ListPar.addAll (getKeyParsList (key)) }} return ListPar;}}
Usage of business module
@ Override @ ExtCacheable (key = "Leaders+#p0+#p1+#p2") / / get the list of leaders public List listLeaders (String leaderGroupId, String uuid, String yearDetailId) {List leadersQuotaDetailList = sysIndexMapper.listLeaders (leaderGroupId, uuid, yearDetailId); return leadersQuotaDetailList;}
How to use the expiration time of business module. It expires in 5 minutes.
@ Override @ ExtCacheable (key = "mobileCacheFlag", expireTime = 60 * 5) public int cacheFlag () {int mobileCacheFlag = 1; mobileCacheFlag = sysIndexMapper.cacheFlag (); return mobileCacheFlag;}
Screenshot of Redis
This is the answer to the question about redis@Cacheable comments and how to set the expiration time. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
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.