• 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. }

  • 相关阅读:
    IIS系统结构
    Spring Cloud Seata 分布式事务学习总结
    19-springcloud(中)
    用HTML+CSS做一个漂亮简单的花店网页【免费的学生网页设计成品】
    启发式算法之蚁群算法
    MS SQL Server partition by 函数实战 统计与输出
    SystemVerilog——class类
    09_CSS3多媒体查询
    二叉树的OJ题——C++
    西电系统分析与设计期末复习笔记
  • 原文地址:https://blog.csdn.net/softshow1026/article/details/134340493