Spring 缓存注解这样用,太香了!
作者最近在开发公司项目时使用到 Redis 缓存,并在翻看前人代码时,看到了一种关于 @Cacheable 注解的自定义缓存有效期的解决方案,感觉比较实用,因此作者自己拓展完善了一番后分享给各位。
Spring 缓存常规配置
Spring Cache 框架给我们提供了 @Cacheable 注解用于缓存方法返回内容。但是 @Cacheable 注解不能定义缓存有效期。这样的话在一些需要自定义缓存有效期的场景就不太实用。
按照 Spring Cache 框架给我们提供的 RedisCacheManager 实现,只能在全局设置缓存有效期。这里给大家看一个常规的 CacheConfig 缓存配置类,代码如下,
@EnableCaching
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
...
private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
}
private RedisSerializer<Object> valueSerializer() {
return new GenericFastJsonRedisSerializer();
}
public static final String CACHE_PREFIX = "crowd:";
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
//设置key为String
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
//设置value为自动转Json的Object
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
.computePrefixWith(name -> CACHE_PREFIX + name + ":")
.entryTtl(Duration.ofSeconds(600));
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(Objects.requireNonNull(redisConnectionFactory));
return new RedisCacheManager(redisCacheWriter, config);
}
}
这里面简单对 RedisCacheConfiguration 缓存配置做一下说明:
serializeKeysWith():设置 Redis 的 key 的序列化规则。erializeValuesWith():设置 Redis 的 value 的序列化规则。computePrefixWith():计算 Redis 的 key 前缀。entryTtl():全局设置@Cacheable注解缓存的有效期。
那么使用如上配置生成的 Redis 缓存 key 名称是什么样得嘞?这里用开源项目 crowd-admin 的 ConfigServiceImpl 类下 getValueByKey(String key) 方法举例,
@Cacheable(value = "configCache", key = "#root.methodName + '_' + #root.args[0]")
@Override
public String getValueByKey(String key) {
QueryWrapper<Config> wrapper = new QueryWrapper<>();
wrapper.eq("configKey", key);
Config config = getOne(wrapper);
if (config == null) {
return null;
}
return config.getConfigValue();
}
执行此方法后,Redis 中缓存 key 名称如下,
crowd:configCache:getValueByKey_sys.name

ttl 过期时间是 287,跟我们全局设置的 300 秒基本是一致的。此时假如我们想把 getValueByKey 方法的缓存有效期单独设置为 600 秒,那我们该如何操作嘞?
@Cacheable 注解默认是没有提供有关缓存有效期设置的。想要单独修改 getValueByKey 方法的缓存有效期只能修改全局的缓存有效期。那么有没有别的方法能够为 getValueByKey 方法单独设置缓存有效期嘞?当然是有的,大家请往下看。
自定义 MyRedisCacheManager 缓存
其实我们可以通过自定义 MyRedisCacheManager 类继承 Spring Cache 提供的 RedisCacheManager 类后,重写 createRedisCache(String name, RedisCacheConfiguration cacheConfig) 方法来完成自定义缓存有效期的功能,代码如下,
public class MyRedisCacheManager extends RedisCacheManager {
public MyRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
super(cacheWriter, defaultCacheConfiguration);
}
@Override
protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
String[] array = StringUtils.split(name, "#");
name = array[0];
// 解析 @Cacheable 注解的 value 属性用以单独设置有效期
if (array.length > 1) {
long ttl = Long.parseLong(array[1]);
cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
}
return super.createRedisCache(name, cacheConfig);
}
}
MyRedisCacheManager 类逻辑如下,
- 继承
Spring Cache提供的RedisCacheManager类。 - 重写
createRedisCache(String name, RedisCacheConfiguration cacheConfig)方法。 - 解析 name 参数,根据
#字符串进行分割,获取缓存 key 名称以及缓存有效期。 - 重新设置缓存 key 名称以及缓存有效期。
- 调用父类的
createRedisCache(name, cacheConfig)方法来完成缓存写入。
接着我们修改下 CacheConfig 类的 cacheManager 方法用以使用 MyRedisCacheManager 类。代码如下,
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new MyRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), defaultCacheConfig());
}
private RedisCacheConfiguration defaultCacheConfig() {
return RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
.computePrefixWith(name -> CACHE_PREFIX + name + ":")
.entryTtl(Duration.ofSeconds(600));
}
最后在使用 @Cacheable 注解时,在原有 value 属性的 configCache 值后添加 #600,单独标识缓存有效期。代码如下,
@Cacheable(value = "configCache#600", key = "#root.methodName + '_' + #root.args[0]")
@Override
public String getValueByKey(String key) {
...
}
看下 getValueByKey 方法生成的 Redis 缓存 key 有效期是多久。如下,

OK,看到是 590 秒有效期后,我们就大功告成了。到这里我们就完成了对 @Cacheable 注解的自定义缓存有效期功能开发。
关注公众号【waynblog】每周分享技术干货、开源项目、实战经验、国外优质文章翻译等,您的关注将是我的更新动力!
Spring 缓存注解这样用,太香了!的更多相关文章
- Spring 缓存注解解析过程
Spring 缓存注解解析过程 通过 SpringCacheAnnotationParser 的 parseCacheAnnotations 方法解析指定方法或类上的缓存注解, @Cacheable ...
- Spring缓存注解@Cache使用
参考资料 http://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/ http://swiftlet.net/archive ...
- Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用(转)
原文地址:https://www.cnblogs.com/fashflying/p/6908028.html 从3.1开始,Spring引入了对Cache的支持.其使用方法和原理都类似于Spring对 ...
- Spring 缓存注解之@Cacheable,@CacheEvit
Spring引入了Cache的支持,其使用方法类似于Spring对事务的支持.Spring Cache是作用于方法上的,其核心思想是,当我们调用一个缓存方法时,把该方法参数和返回结果作为一个键值对存放 ...
- 【Spring】22、Spring缓存注解@Cache使用
缓存注解有以下三个: @Cacheable @CacheEvict @CachePut @Cacheable(value=”accountCache”),这个注释的意思是,当调用这个 ...
- Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用
从3.1开始,Spring引入了对Cache的支持.其使用方法和原理都类似于Spring对事务管理的支持.Spring Cache是作用在方法上的,其核心思想是这样的:当我们在调用一个缓存方法时会把该 ...
- Spring缓存注解
从3.1开始,Spring引入了对Cache的支持.其使用方法和原理都类似于Spring对事务管理的支持.Spring Cache是作用在方法上的,其核心思想是这样的:当我们在调用一个缓存方法时会把该 ...
- Spring – 缓存注解
Spring缓存抽象概述 Spring框架自身并没有实现缓存解决方案,但是从3.1开始定义了org.springframework.cache.Cache和org.springframework.ca ...
- Spring缓存注解@CachePut , @CacheEvict,@CacheConfig使用
Cacheable CachePut CacheEvict CacheConfig 开启缓存注解 @Cacheable @Cacheable是用来声明方法是可缓存的.将结果存储到缓存中以便后续使用相同 ...
- 详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用
https://blog.csdn.net/u012240455/article/details/80844361 注释介绍 @Cacheable @Cacheable 的作用 主要针对方法配置,能够 ...
随机推荐
- 从 iOS App 启动速度看如何为基础性能保驾护航
1 前言 启动是App给用户的第一印象,一款App的启动速度,不单单是用户体验的事情,往往还决定了它能否获取更多的用户.所以到了一定阶段App的启动优化是必须要做的事情.App启动基本分为以下两种 1 ...
- 与AI对话 -- 20230221 -- linux 性能分析相关的软件包
linux 性能分析相关的软件包有哪些,各自包含了哪些命令 sysstat:sysstat 包含了丰富的监控系统性能的工具,例如 sar(系统性能分析器).iostat(设备 IO 状态分析器).mp ...
- .NET Core多线程 (1) Thread与Task
去年换工作时系统复习了一下.NET Core多线程相关专题,学习了一线码农老哥的<.NET 5多线程编程实战>课程,我将复习的知识进行了总结形成本专题.同时也特别推荐有兴趣的读者去学习一线 ...
- BurpSuite设置上游代理访问内网
转载原文 原理知道了后,开始! 拿到B的shell后,添加路由 拿到B的shell后,开启sock4 在D主机上设置好 最后成功抓到包
- java if switch
强制类型转换 注意事项:大的转小的需要强制转换 例如: double b=3.4 int小于double所以想让int=b,要在b后面加个(int)b. int a=(int)b 得到3 因为大 ...
- MongoDB索引操作和执行计划Explain()详解
一.索引操作 说明,下面的内容举例时,以"dailyTrip"collection为例. 字段内容如下: { "_id" : ObjectId("63 ...
- mall :rabbit项目源码解析
目录 一.mall开源项目 1.1 来源 1.2 项目转移 1.3 项目克隆 二.RabbitMQ 消息中间件 2.1 rabbit简介 2.2 分布式后端项目的使用流程 2.3 分布式后端项目的使用 ...
- Anaconda平台下从0到1安装TensorFlow环境详细教程(Windows10+Python)
1.安装Anaconda Anaconda下载链接:Free Download | Anaconda 下载完成之后,开始安装,修改安装路径至指定文件夹下,由于安装过程比较简单,此处略过: 2.Tens ...
- vue3 甘特图(一):选择与初始化甘特图
vue3 甘特图(一) 1.功能使用背景: 甘特图是一种项目管理工具,以图形直观的方式显示项目的时间轴和任务计划,为了可扩展和定制相关任务的开发,故此选择dhtmlx-gantt 2.vue3 初始化 ...
- minio 支持object搜索方案
minio支持上传时对object打标签,查询时可以根据标签做筛选.但是有ftp上传文件的需求,导致无法给object打标签.并且也不清楚minio对于根据标签的筛选性能如何,因此我们打算将objec ...