• Spring 缓存注解


    Spring Cache 框架给我们提供了 @Cacheable 注解用于缓存方法返回内容。但是 @Cacheable 注解不能定义缓存有效期。这样的话在一些需要自定义缓存有效期的场景就不太实用。

    按照 Spring Cache 框架给我们提供的 RedisCacheManager 实现,只能在全局设置缓存有效期。这里给大家看一个常规的 CacheConfig 缓存配置类,代码如下,

    1. @EnableCaching
    2. @Configuration
    3. public class CacheConfig extends CachingConfigurerSupport {
    4. ...
    5. private RedisSerializer<String> keySerializer() {
    6. return new StringRedisSerializer();
    7. }
    8. private RedisSerializer<Object> valueSerializer() {
    9. return new GenericFastJsonRedisSerializer();
    10. }
    11. public static final String CACHE_PREFIX = "crowd:";
    12. @Bean
    13. public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    14. // 配置序列化(解决乱码的问题)
    15. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
    16. //设置keyString
    17. .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
    18. //设置value为自动转Json的Object
    19. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
    20. .computePrefixWith(name -> CACHE_PREFIX + name + ":")
    21. .entryTtl(Duration.ofSeconds(600));
    22. RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(Objects.requireNonNull(redisConnectionFactory));
    23. return new RedisCacheManager(redisCacheWriter, config);
    24. }
    25. }

    自定义 MyRedisCacheManager 缓存

    其实我们可以通过自定义 MyRedisCacheManager 类继承 Spring Cache 提供的 RedisCacheManager 类后,重写 createRedisCache(String name, RedisCacheConfiguration cacheConfig) 方法来完成自定义缓存有效期的功能,代码如下

    1. public class MyRedisCacheManager extends RedisCacheManager {
    2. public MyRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
    3. super(cacheWriter, defaultCacheConfiguration);
    4. }
    5. @Override
    6. protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
    7. String[] array = StringUtils.split(name, "#");
    8. name = array[0];
    9. // 解析 @Cacheable 注解的 value 属性用以单独设置有效期
    10. if (array.length > 1) {
    11. long ttl = Long.parseLong(array[1]);
    12. cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
    13. }
    14. return super.createRedisCache(name, cacheConfig);
    15. }
    16. }

  • 相关阅读:
    vue3-webpack遇到Eslint各种报错
    前端基础之《Bootstrap(8)—CSS组件_导航条》
    推荐10个堪称神器的 Java 学习网站
    Sping源码(九)—— Bean的初始化(非懒加载)— doGetBean
    关于Java Integer和Long使用equals直接比较
    Proteus + Keil单片机仿真教程(六)多位LED数码管的动态显示
    【方向盘】使用IDEA的60+个快捷键分享给你,权为了提效(运行/调试篇)
    佳音通讯400电话在线选号服务
    (入门自用)--Linux--文件系统--磁盘--1019
    【蓝桥备战】快速排序+归并排序+二分查找 基本实现
  • 原文地址:https://blog.csdn.net/softshow1026/article/details/134340493