application.yml配置

spring: 
  cache:
    type: REDIS
    redis:
      time-to-live: PT300S # 默认缓存秒数
      cache-null-values: false # 是否缓存空值

支持指定cacheNames设置缓存时长

/**
 * Redis配置类
 *
 * @author ZJJ
 */
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
public class RedisCacheConfig extends CachingConfigurerSupport {
    @Autowired
    private CacheProperties cacheProperties;

@Autowired
    private RedisConnectionFactory redisConnectionFactory;

@Bean
    @Primary
    public RedisTemplate<Serializable, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Serializable, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

// 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

jackson2JsonRedisSerializer.setObjectMapper(om);

// 设置value的序列化规则和 key的序列化规则
        redisTemplate.setDefaultSerializer(new StringRedisSerializer(StandardCharsets.UTF_8));// 默认为:JdkSerializeable
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

/**
     * 默认缓存管理器
     * <br>
     * 使用样例1:@Cacheable(cacheNames = "demoCache", key = "#id")// 5分钟
     * 使用样例2:@Cacheable(cacheNames = "userCache", key = "#id")// 默认10分钟
     * 使用样例3:@Cacheable(cacheNames = "customCache#60", key = "#id") // 自定义缓存60秒
     */
    @Override
    @Bean
    public RedisCacheManager cacheManager() {
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(this.cacheProperties.getRedis().getTimeToLive());

// 针对不同cacheName,设置不同的过期时间
        Map<String, RedisCacheConfiguration> initialCacheConfiguration = new LinkedHashMap<String, RedisCacheConfiguration>() {
            {
                this.put("demoCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5)));
                // this.put("userCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10))); // 10分钟
                // TODO 其他自定义缓存时长...
            }
        };

// return RedisCacheManager.builder(this.redisConnectionFactory).cacheDefaults(defaultCacheConfig)
        // .withInitialCacheConfigurations(initialCacheConfiguration).build();
        return new CustomRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(this.redisConnectionFactory), defaultCacheConfig,
                initialCacheConfiguration);
    }
}

/**
 * 自定义Redis缓存管理器 - 支持缓存名#缓存秒数
 *
 * @author ZJJ
 */
class CustomRedisCacheManager extends RedisCacheManager {
    public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration,
            Map<String, RedisCacheConfiguration> initialCacheConfigurations) {
        super(cacheWriter, defaultCacheConfiguration, initialCacheConfigurations, true);
    }

@Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] array = name.split("#");
        name = array[0];
        if (array.length > 1) { // 解析TTL
            cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(Long.parseLong(array[1]))); // 秒
        }
        return super.createRedisCache(name, cacheConfig);
    }
}

调整evict方法支持key通配符

重写 org.springframework.data.redis.cache.RedisCache

/*
     * 使用样例:@CacheEvict(cacheNames = "loginCache", key = "test-*")
     */
    @Override
    public void evict(Object key) {
        if (key instanceof String && ((String) key).endsWith("*")) {// 通配符删除
            byte[] pattern = this.conversionService.convert(this.createCacheKey(key), byte[].class);
            this.cacheWriter.clean(this.name, pattern);
        } else {// 单一key删除
            this.cacheWriter.remove(this.name, this.createAndConvertCacheKey(key));
        }
    }

Spring-Redis缓存业务优化(通配符删除、两种自定义缓存时长)的更多相关文章

  1. MySQL关闭查询缓存(QC)的两种方法

    MySQL Query Cache 会缓存select 查询,安装时默认是开启的,但是如果对表进行INSERT, UPDATE, DELETE, TRUNCATE, ALTER TABLE, DROP ...

  2. Redis安装、主从配置及两种高可用集群搭建

    Redis安装.主从配置及两种高可用集群搭建 一.            准备 Kali Linux虚拟机 三台:192.168.154.129.192.168.154.130.192.168.154 ...

  3. [leetcode]159. Longest Substring with At Most Two Distinct Characters至多包含两种字符的最长子串

    Given a string s , find the length of the longest substring t  that contains at most 2 distinct char ...

  4. Redis持久化存储(AOF与RDB两种模式)

    Redis中数据存储模式有2种:cache-only,persistence; cache-only即只做为“缓存”服务,不持久数据,数据在服务终止后将消失,此模式下也将不存在“数据恢复”的手段,是一 ...

  5. Guava的两种本地缓存策略

    Guava的两种缓存策略 缓存在很多场景下都需要使用,如果电商网站的商品类别的查询,订单查询,用户基本信息的查询等等,针对这种读多写少的业务,都可以考虑使用到缓存.在一般的缓存系统中,除了分布式缓存, ...

  6. 【Spring】SpringMVC非注解配置的两种方式

    目录结构: contents structure [+] SpringMVC是什么 Spring MVC的设计原理 SpringMVC配置的第一种方式 1,复制Jar包 2,Web.xml文件 3,M ...

  7. UWP开发中两种网络图片缓存方法

    通常情况下,我们的程序需要从服务器读取图片,但如果需要不止一次读取某一张图片的话,就需要做本地缓存了,这样既为用户省一点流量,又能显得你的APP很快. 假如你已经知道了某一张图片的地址,那么第一件事就 ...

  8. Spring Boot + Vue 前后端分离,两种文件上传方式总结

    在Vue.js 中,如果网络请求使用 axios ,并且使用了 ElementUI 库,那么一般来说,文件上传有两种不同的实现方案: 通过 Ajax 实现文件上传 通过 ElementUI 里边的 U ...

  9. spring boot 学习10 定义springboot的两种方法

    使用spring boot的两种方法: A:继承spring-boot-starter-parent项目 这种方式很简单,只需要在POM里面添加parent父工程即可. B: 如果你不喜欢继承spri ...

随机推荐

  1. QT学习笔记(一)——Helloworld

    QT学习笔记(一)--Helloworld 一.调试的基本方法: Log调试法 --在代码中加入一定的打印语句 --打印程序状态和关键变量的值 断点调试法: --在开发环境中的对应代码行加上断点 -- ...

  2. Docker-Compose入门-(转载)

    Compose 是一个用户定义和运行多个容器的 Docker 应用程序.在 Compose 中你可以使用 YAML 文件来配置你的应用服务.然后,只需要一个简单的命令,就可以创建并启动你配置的所有服务 ...

  3. flink Checkpoint优化

    一.设置最小时间间隔 当flink应用开启Checkpoint功能,并配置Checkpoint时间间隔,应用中就会根据指定的时间间隔周期性地对应用进行Checkpoint操作.默认情况下Checkpo ...

  4. Python数模笔记-Scipy库(1)线性规划问题

    1.最优化问题建模 最优化问题的三要素是决策变量.目标函数和约束条件. (1)分析影响结果的因素是什么,确定决策变量 (2)决策变量与优化目标的关系是什么,确定目标函数 (3)决策变量所受的限制条件是 ...

  5. 第5讲 | 从物理层到MAC层:如何在宿舍里自己组网玩联机游戏?

    第一层(物理层) 水晶头要做交叉线,用的就是所谓的 1-3.2-6 交叉接法. 有一个叫做 Hub 的东西,也就是集线器.这种设备有多个口,可以将宿舍里的多台电脑连接起来.但是,和交换机不同,集线器没 ...

  6. Linux(CentOS7)下rpm安装MySQL8.0.16

    记录一下自己在 CentOS7 下 rpm 安装 MySQL8.0.16 的过程. 一.准备工作 1. 下载MySQL所需要的安装包 从 MySQL官网 下载,上传至 CentOS 系统 /usr/l ...

  7. 日常Bug排查-抛异常不回滚

    日常Bug排查-抛异常不回滚 前言 日常Bug排查系列都是一些简单Bug排查,笔者将在这里介绍一些排查Bug的简单技巧,同时顺便积累素材_. Bug现场 最近有人反映java应用操作数据库的时候,抛异 ...

  8. X-Deep Learning功能模块

    X-Deep Learning功能模块 特征体系 样本 特征 网络 数据准备 样本格式 使用DataReader读取数据 自定义python reader 定义模型 稀疏部分 稠密部分 优化器 训练模 ...

  9. SpringBoot系列——cache缓存

    前言 日常开发中,缓存是解决数据库压力的一种方案,通常用于频繁查询的数据,例如新闻中的热点新闻,本文记录springboot中使用cache缓存. 官方文档介绍:https://docs.spring ...

  10. postman之内建变量的基础应用

    一.Postman有以下内建变量,适合一次性使用:{{$guid}}//生成GUID{{$timestamp}}//当前时间戳{{$randomInt}}//0-1000的随机整数 简单应用举例: 二 ...