Springboot统一给redis缓存的Key加前缀

第一步:配置redis

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.keyvalue.core.mapping.KeyPrefix;
import org.springframework.data.keyvalue.core.query.KeyValueQuery;
import java.time.Duration;
 
@Configuration
public class RedisConfig {
    public static final String redisPrefix="xxxx:"; 
    @Bean
    public RedisTemplate<String, String> redisTemplate(StringRedisTemplate stringRedisTemplate) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setKeySerializer(stringRedisTemplate.getKeySerializer());
        template.setValueSerializer(stringRedisTemplate.getValueSerializer());
        template.setHashKeySerializer(stringRedisTemplate.getHashKeySerializer());
        template.setHashValueSerializer(stringRedisTemplate.getHashValueSerializer());
        template.setEnableTransactionSupport(true);
        template.setConnectionFactory(stringRedisTemplate.getConnectionFactory());
 
        // 设置key的前缀
        KeyPrefix keyPrefix = new KeyPrefix() {
            @Override
            public byte[] prefix(String key) {
                return (redisPrefix + ":" + key).getBytes();
            }
        };
        template.setKeyGenerator(keyPrefix);
 
        return template;
    }
}

第二步:在使用

java 复制代码
//在代码中注入RedisTemplate
@Autowired
private RedisTemplate<String, String> redisTemplate;
 
//写个方法调用
public void setValue(String key, String value) {
   // //使用,添加一个缓存,添加后使用redis管理工具查看,此时会发现key将会自动加上前缀"redisPrefix:"
    redisTemplate.opsForValue().set(key, value, Duration.ofMinutes(300));
   
}
相关推荐
Flittly3 小时前
【AgentScope Java新手村系列】(19)多模态-图像音频视频
java·spring boot·spring
cfm_29145 小时前
SpringBoot启动原理
java·spring boot·spring
漫随流水6 小时前
Java——springboot web案例
java·开发语言·spring boot
干到60岁退休的码农11 小时前
SpringBoot整合Mybatis-plus
spring boot·后端·mybatis
C137的本贾尼13 小时前
第九篇:微服务与分布式——把一个大系统拆成多个小服务
xml·spring boot·后端
cfm_291413 小时前
SpringBoot自定义Starter
java·spring boot·后端
霸道流氓气质13 小时前
Windows 本地搭建 CDC 全链路测试环境(Kafka+Canel+binlog+SpringBoot)
windows·spring boot·kafka
Demon_Hao13 小时前
Spring Boot 4、JDK 25 与 GraalVM:Java 云原生进化,能否撼动 Go 的地位?
java·spring boot·云原生
月落星还在1 天前
Spring MVC 与 Spring Boot:从“手动挡”到“自动驾驶”的进化论,兼谈前后端分离的哲学
spring boot·spring·云原生·mvc
码农进化录1 天前
Java 程序员的 AI 进化论 | Spring Boot 接入 OpenAI 的六个坑,全帮你踩了
java·spring boot·openai