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

What is the method of specifying expiration time for Spring @ Cacheable

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "what is the method of specifying failure time of Spring @ Cacheable". In daily operation, I believe many people have doubts about what is the method of specifying failure time of Spring @ Cacheable. The editor has consulted all kinds of materials and sorted out simple and useful operation methods, hoping to help you answer the doubts of "what is the method of specifying failure time of Spring @ Cacheable"! Next, please follow the editor to study!

Spring @ Cacheable specified expiration time new version configuration @ Configuration@EnableCachingpublic class RedisCacheConfig {@ Bean public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer () {return (builder)-> {for (Map.Entry entry: RedisCacheName.getCacheMap () .entrySet ()) {builder.withCacheConfiguration (entry.getKey (), RedisCacheConfiguration.defaultCacheConfig () .entryTtl (entry.getValue ();}} } public static class RedisCacheName {public static final String CACHE_10MIN = "CACHE_10MIN"; @ Getter private static final Map cacheMap; static {cacheMap = ImmutableMap.builder () .put (CACHE_10MIN, Duration.ofSeconds (10L)) .build ();} older version configuration interface CacheNames {String CACHE_15MINS = "sssss:cache:15m" / * * 30-minute cache group * / String CACHE_30MINS = "sssss:cache:30m"; / * * 60-minute cache group * / String CACHE_60MINS = "sssss:cache:60m"; / * * 180min cache group * / String CACHE_180MINS = "sssss:cache:180m" } @ Component public class RedisCacheCustomizer implements CacheManagerCustomizer {/ * * CacheManager cache custom initialization is relatively early Try not to @ autowired other spring components * / @ Override public void customize (RedisCacheManager cacheManager) {/ / Custom cache name's expiration time Map expires = ImmutableMap.builder () .put (CacheNames.CACHE_15MINS, TimeUnit.MINUTES.toSeconds (15)) .put (CacheNames.CACHE_30MINS TimeUnit.MINUTES.toSeconds (30)) .put (CacheNames.CACHE_60MINS, TimeUnit.MINUTES.toSeconds (60)) .put (CacheNames.CACHE_180MINS, TimeUnit.MINUTES.toSeconds (180)) .build () / / spring cache is based on the expiration of the cache name lookup cache. If it cannot be found, the default value is cacheManager.setDefaultExpiration (TimeUnit.MINUTES.toSeconds (30)); cacheManager.setExpires (expires);}} @ Cacheable (key = "key", cacheNames = CacheNames.CACHE_15MINS) public String demo2 (String key) {return "abc" + key } @ Cacheable cache expiration time policy default implementation and extension

The previous understanding of Spring cache is that after each cache setting, repeated requests will refresh the cache time, but the problem troubleshooting and reading the source code shows that it is quite different from your own understanding. All you think is just what you think!

Background

Currently, the spring cache used by the project is mainly CacheManager, Cache and @ Cacheable annotations. The existing cache annotations of Spring cannot set the expiration time of each annotation separately. The official explanation given by Spring: Spring Cache is an abstract rather than a cache implementation.

Therefore, the cache expiration time (TTL) strategy depends on the underlying cache middleware, for example: ConcurrentMap does not support expiration time, while Redis supports expiration time.

Spring Cache Redis implementation

Spring cache annotations @ Cacheable underlying CacheManager and Cache if you use the Redis scheme, after the cache data is set for the first time, each repeated request to read the cache in the same way will not refresh the expiration time. This is the default behavior of Spring (affected by some caches, I always thought that each read cache would also refresh the cache expiration time).

You can see the source code:

Org.springframework.cache.interceptor.CacheAspectSupport#execute (org.springframework.cache.interceptor.CacheOperationInvoker, java.lang.reflect.Method, org.springframework.cache.interceptor.CacheAspectSupport.CacheOperationContexts)

Private Object execute (final CacheOperationInvoker invoker, Method method, CacheOperationContexts contexts) {/ / Special handling of synchronized invocation if (contexts.isSynchronized ()) {CacheOperationContext context = contexts.get (CacheableOperation.class). Iterator (). Next () If (isConditionPassing (context, CacheOperationExpressionEvaluator.NO_RESULT)) {Object key = generateKey (context, CacheOperationExpressionEvaluator.NO_RESULT); Cache cache = context.getCaches (). Iterator (). Next () Try {return wrapCacheValue (method, cache.get (key, ()-> unwrapReturnValue (invokeOperation (invoker) } catch (Cache.ValueRetrievalException ex) {/ / The invoker wraps any Throwable in a ThrowableWrapper instance so we / / can just make sure that one bubbles up the stack. Throw (CacheOperationInvoker.ThrowableWrapper) ex.getCause ();}} else {/ / No caching required, only call the underlying method return invokeOperation (invoker) }} / / Process any early evictions processCacheEvicts (contexts.get (CacheEvictOperation.class), true, CacheOperationExpressionEvaluator.NO_RESULT); / / Check if we have a cached item matching the conditions Cache.ValueWrapper cacheHit = findCachedItem (contexts.get (CacheableOperation.class)) / / Collect puts from any @ Cacheable miss, if no cached item is found List cachePutRequests = new LinkedList (); if (cacheHit = = null) {collectPutRequests (contexts.get (CacheableOperation.class), CacheOperationExpressionEvaluator.NO_RESULT, cachePutRequests);} Object cacheValue Object returnValue; if (cacheHit! = null & &! hasCachePut (contexts)) {/ / If there are no put requests, just use the cache hit cacheValue = cacheHit.get (); returnValue = wrapCacheValue (method, cacheValue) } else {/ / Invoke the method if we don't have a cache hit returnValue = invokeOperation (invoker); cacheValue = unwrapReturnValue (returnValue);} / / Collect any explicit @ CachePuts collectPutRequests (contexts.get (CachePutOperation.class), cacheValue, cachePutRequests) / / Process any collected put requests, either from @ CachePut or a @ Cacheable miss for (CachePutRequest cachePutRequest: cachePutRequests) {cachePutRequest.apply (cacheValue);} / / Process any late evictions processCacheEvicts (contexts.get (CacheEvictOperation.class), false, cacheValue); return returnValue;}

So if we need to control the cache invalidation strategy on our own, we may need some development work, as follows.

Self-refresh of Spring Cache failure time

1: customize the Cache component based on Spring, rewrite the get method and refresh the expiration time. It is relatively simple and not difficult; the code is not posted here.

2: you can use background threads to refresh the cache regularly to achieve the refresh time.

3: use the spring data redis module, which provides information about the TTL update strategy, which can be found in: org.springframework.data.redis.core.PartialUpdate

Note:

The Spring annotation for @ Cacheable is provided by spring-context, and the cache abstraction provided by spring-context is a set of standards rather than an implementation.

PartialUpdate is provided by spring-data-redis, and spring-data-redis is a set of spring implementation scheme for redis.

At this point, the study on "what is the method of specifying the expiration time of Spring @ Cacheable" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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