springboot-cache+redis 为指定名称缓存设置独立超时时间

2024-05-24 12:23:12 浏览数 (2)

版本

spring-boot: 3.2.2

方案

注册 RedisCacheManagerBuilderCustomizer Bean对指定名称缓存进行定制

代码语言:javascript复制
@Bean
RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
    return builder -> builder.withCacheConfiguration(
    		// @Cacheable 注解使用的cacheNames参数值
            CACHE_NAME_1,
            builder
		            // 获取全局配置
                    .cacheDefaults()
                    // 在全局配置基础上添加超时时间配置
                    .entryTtl(Duration.ofSeconds(60))
    ).withCacheConfiguration(
            CACHE_NAME_2,
            builder
                    .cacheDefaults()
                    .entryTtl(Duration.ofSeconds(60))
    );
}

源码

redis缓存管理器自动化配置 org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration

代码语言:javascript复制
...
@Conditional(CacheCondition.class)
class RedisCacheConfiguration {
	...
	@Bean
	RedisCacheManager cacheManager(CacheProperties cacheProperties, CacheManagerCustomizers cacheManagerCustomizers,
			ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
			ObjectProvider<RedisCacheManagerBuilderCustomizer> redisCacheManagerBuilderCustomizers,
			RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) {
		// 如果存在redisCacheConfiguration则使用redisCacheConfiguration,否则读取配置属性构造
		RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory)
			.cacheDefaults(
					determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader()));
		// 使用上一步构造的默认配置初始化所有名称的缓存配置
		List<String> cacheNames = cacheProperties.getCacheNames();
		if (!cacheNames.isEmpty()) {
			builder.initialCacheNames(new LinkedHashSet<>(cacheNames));
		}
		if (cacheProperties.getRedis().isEnableStatistics()) {
			builder.enableStatistics();
		}
		// 应用redis缓存管理器定制器
		redisCacheManagerBuilderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
		// 应用公共缓存管理器定制器
		return cacheManagerCustomizers.customize(builder.build());
	}
	...
}

0 人点赞