spring缓存注解@Cacheable和@CacheEvict,设置过期时间和批量模糊删除
配置
CacheManager 类
直接上代码
key前缀配置
spring-data-redis高版本的话, 直接在yaml配置即可,但是我的是2.1.18,不知道为什么没生效,看了下两个版本设置前缀的方法也不一样,应该是版本问题。
或者直接在配置类中设置,如下配置computePrefixWith() 如果有问题,打断点看RedisCache的createCacheKey方法
spring:
	cache:
		redis:
			key-prefix: xxx
			
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
@Configuration
public class CacheConfig {
   
   
    /**
     * 最终调用 org.springframework.data.redis.cache.RedisCacheConfiguration#getKeyPrefixFor(java.lang.String)
     */
    private static final CacheKeyPrefix DEFAULT_CACHE_KEY_PREFIX = cacheName -> "edu:service_spring:"+cacheName+":";
    @Bean
    public CacheManager cacheManager
 
                   
                   
                   
                   本文详细介绍了如何在Spring中配置缓存,包括使用@Cacheable和@CacheEvict注解,设置Redis缓存的过期时间,以及实现批量模糊删除缓存。通过自定义RedisCacheManager和RedisCache,实现了根据注解的value动态设置过期时间,并提供了针对特定key后缀的批量删除操作。同时,文章还展示了如何处理缓存key的前缀配置和序列化问题。
本文详细介绍了如何在Spring中配置缓存,包括使用@Cacheable和@CacheEvict注解,设置Redis缓存的过期时间,以及实现批量模糊删除缓存。通过自定义RedisCacheManager和RedisCache,实现了根据注解的value动态设置过期时间,并提供了针对特定key后缀的批量删除操作。同时,文章还展示了如何处理缓存key的前缀配置和序列化问题。
           最低0.47元/天 解锁文章
最低0.47元/天 解锁文章
                           
                       
       
           
                 
                 
                 
                 
                 
                
               
                 
                 
                 
                 
                
               
                 
                 扫一扫
扫一扫
                     
              
             
                   3429
					3429
					
 被折叠的  条评论
		 为什么被折叠?
被折叠的  条评论
		 为什么被折叠?
		 
		  到【灌水乐园】发言
到【灌水乐园】发言                                
		 
		 
    
   
    
   
             
            


 
            