You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.0.x迁移:基于Jedis创建RedisCacheManager的方法

Spring Boot 3.0.x 下基于Jedis创建RedisCacheManager的正确方式

Spring Boot 1.5.x到3.0.x的升级中,Spring Data Redis的API变化较大,RedisCacheManager的构造器不再直接接收RedisTemplate,而是需要通过RedisCacheWriter和RedisCacheConfiguration来构建。以下是适配你原有逻辑的实现方式:

适配后的CacheManager Bean实现

@Bean
public CacheManager cacheManager1(RedisTemplate<Object, Object> redisTemplate) {
    // 创建非锁模式的RedisCacheWriter,基于RedisTemplate的连接工厂
    RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());

    // 构建默认缓存配置,对齐原有逻辑
    RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
            // 设置默认过期时间为300秒(对应原setDefaultExpiration(300))
            .entryTtl(Duration.ofSeconds(300))
            // 开启缓存键前缀(对应原setUsePrefix(true)),使用默认的前缀生成规则
            .computePrefixWith(CacheKeyPrefix.simple())
            // 复用RedisTemplate的序列化器,避免序列化不一致问题
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getKeySerializer()))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));

    // 配置特定缓存的自定义过期时间(对应原setExpires方法)
    Map<String, RedisCacheConfiguration> customCacheConfigs = new HashMap<>();
    customCacheConfigs.put("DELIVERED_DLR_MESSAGE_PART_COUNT_MAP",
            defaultCacheConfig.entryTtl(Duration.ofSeconds(1000)));
    customCacheConfigs.put("FAILED_DLR_MESSAGE_PART_COUNT_MAP",
            defaultCacheConfig.entryTtl(Duration.ofSeconds(1000)));

    // 构建并返回RedisCacheManager
    return RedisCacheManager.builder(cacheWriter)
            .cacheDefaults(defaultCacheConfig)
            .withInitialCacheConfigurations(customCacheConfigs)
            .build();
}

关键变化说明

  • RedisCacheWriter:负责Redis底层的缓存读写操作,nonLockingRedisCacheWriter是无锁实现(默认推荐),如果需要锁机制可以用lockingRedisCacheWriter。
  • RedisCacheConfiguration:替代原有通过setter设置的配置项,比如:
    • entryTtl(Duration)替代setDefaultExpiration(Long),用Duration更清晰表达时间单位
    • computePrefixWith(CacheKeyPrefix)替代setUsePrefix(true),还可以自定义前缀生成规则
    • 序列化配置:通过serializeKeysWith和serializeValuesWith复用RedisTemplate的序列化器,确保缓存数据和RedisTemplate操作的数据序列化方式一致
  • 特定缓存配置:通过withInitialCacheConfigurations传入配置Map,替代原有的setExpires方法

保留Jedis的注意事项

确保项目中引入了Jedis相关依赖,Spring Boot 3.x可以直接引入:

<!-- Maven依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis-jedis</artifactId>
</dependency>

或者在application配置文件中指定Redis客户端类型(如果使用spring-boot-starter-data-redis):

spring.data.redis.client-type=jedis
# 其他Redis基础配置
spring.data.redis.host=your-redis-host
spring.data.redis.port=6379

内容的提问来源于stack exchange,提问作者Aman Bansal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 10:01:42