作者最近在开发公司项目时使用到 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 缓存配置做一下说明:

  1. serializeKeysWith():设置 Redis 的 key 的序列化规则。
  2. erializeValuesWith():设置 Redis 的 value 的序列化规则。
  3. computePrefixWith():计算 Redis 的 key 前缀。
  4. 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 类逻辑如下,

  1. 继承 Spring Cache 提供的 RedisCacheManager 类。
  2. 重写 createRedisCache(String name, RedisCacheConfiguration cacheConfig) 方法。
  3. 解析 name 参数,根据 # 字符串进行分割,获取缓存 key 名称以及缓存有效期。
  4. 重新设置缓存 key 名称以及缓存有效期。
  5. 调用父类的 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 缓存注解这样用,太香了!的更多相关文章

  1. Spring 缓存注解解析过程

    Spring 缓存注解解析过程 通过 SpringCacheAnnotationParser 的 parseCacheAnnotations 方法解析指定方法或类上的缓存注解, @Cacheable ...

  2. Spring缓存注解@Cache使用

    参考资料 http://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/ http://swiftlet.net/archive ...

  3. Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用(转)

    原文地址:https://www.cnblogs.com/fashflying/p/6908028.html 从3.1开始,Spring引入了对Cache的支持.其使用方法和原理都类似于Spring对 ...

  4. Spring 缓存注解之@Cacheable,@CacheEvit

    Spring引入了Cache的支持,其使用方法类似于Spring对事务的支持.Spring Cache是作用于方法上的,其核心思想是,当我们调用一个缓存方法时,把该方法参数和返回结果作为一个键值对存放 ...

  5. 【Spring】22、Spring缓存注解@Cache使用

    缓存注解有以下三个: @Cacheable      @CacheEvict     @CachePut @Cacheable(value=”accountCache”),这个注释的意思是,当调用这个 ...

  6. Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用

    从3.1开始,Spring引入了对Cache的支持.其使用方法和原理都类似于Spring对事务管理的支持.Spring Cache是作用在方法上的,其核心思想是这样的:当我们在调用一个缓存方法时会把该 ...

  7. Spring缓存注解

    从3.1开始,Spring引入了对Cache的支持.其使用方法和原理都类似于Spring对事务管理的支持.Spring Cache是作用在方法上的,其核心思想是这样的:当我们在调用一个缓存方法时会把该 ...

  8. Spring – 缓存注解

    Spring缓存抽象概述 Spring框架自身并没有实现缓存解决方案,但是从3.1开始定义了org.springframework.cache.Cache和org.springframework.ca ...

  9. Spring缓存注解@CachePut , @CacheEvict,@CacheConfig使用

    Cacheable CachePut CacheEvict CacheConfig 开启缓存注解 @Cacheable @Cacheable是用来声明方法是可缓存的.将结果存储到缓存中以便后续使用相同 ...

  10. 详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用

    https://blog.csdn.net/u012240455/article/details/80844361 注释介绍 @Cacheable @Cacheable 的作用 主要针对方法配置,能够 ...

随机推荐

  1. 虚拟化学习:vps和云计算的区别

    1 vps 可以由虚拟机实现,但并不是虚拟机; 虚拟机是云计算的核心,但虚拟机也不等于云主机. 2 vps是面向单台服务器的虚拟化技术,服务器挂了,其上的vps也跟着挂了. 3 云计算是面向服务器集群 ...

  2. 2021-7-7 VUE动态样式

    Vue的动态样式实例1 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> & ...

  3. python-多继承构造函数声明问题

    背景 有场景分别定义两组逻辑,随后有统一入口做基类属性的整合 其中两组逻辑的积累构造函数定义入参不同 设计类继承图如: 实际的使用方式抽象为[使用] 小节 实际开发过程中遇到问题 先说结论 pytho ...

  4. go语言实用工具编写要这样学

    写作目的 本篇章写作有以下目的: 介绍go语言的基础知识,这里你会发现go语言学习成本较低,与python语言相似. 介绍go语言的常用标准库,这里你会发现go语言的标准库已经非常强大,python语 ...

  5. 质量管理 | QC、QA、QM,去QA化与降本增效

    现在国内职业的质量管理都是从 CMMI 和 ISO 质量体系演化过来的,但是能做真正的质量管理的公司很少.质量管理的 QC 偏测试,对最终的产品负责:QA 偏过程,从过程把控质量:QM 偏体系,类似于 ...

  6. 《Kali渗透基础》10. 提权、后渗透

    @ 目录 1:提权 2:Admin 提权为 System 2.1:at 2.2:sc 2.3:SysInternal Suite 2.4:进程注入提权 3:抓包嗅探 4:键盘记录 5:本地缓存密码 5 ...

  7. (2023.7.24)软件加密与解密-2-1-程序分析方法[XDbg].md

    body { font-size: 15px; color: rgba(51, 51, 51, 1); background: rgba(255, 255, 255, 1); font-family: ...

  8. 获取API接口返回的商品详情数据后该如何使用

    获取API接口返回的商品详情数据后,我们可以使用以下方式将其处理和利用: 数据展示:我们可以将API接口返回的商品详情数据以列表.表格.图形等形式展示给用户,以便他们更好地了解商品的基本信息.特征.评 ...

  9. SqlServer表添加字段

    IF NOT EXISTS (SELECT * FROM syscolumns WHERE id=object_id('表名') AND name='字段名') ALTER TABLE 表名 ADD ...

  10. Leetcode刷题笔记——二分法

    二分法是搜索算法中极其典型的方法,其要求输入序列有序并可随机访问.算法思想为 输入:有序数组nums,目的数值target 要求输出:如果target存在在数组中,则输出其index,否则输出-1 将 ...