前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot-cache+redis 为指定名称缓存设置独立超时时间

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

作者头像
路过君
发布2024-05-24 12:23:12
590
发布2024-05-24 12:23:12
举报

版本

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());
	}
	...
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-02-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 版本
  • 方案
  • 源码
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档