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));
   
}
相关推荐
金牌归来发现妻女流落街头26 分钟前
【从SpringBoot到SpringCloud】
java·spring boot·spring cloud
皮卡丘不断更40 分钟前
手搓本地 RAG:我用 Python 和 Spring Boot 给 AI 装上了“实时代码监控”
人工智能·spring boot·python·ai编程
lucky67071 小时前
Spring Boot集成Kafka:最佳实践与详细指南
spring boot·kafka·linq
Coder_Boy_1 小时前
基于Spring AI的分布式在线考试系统-事件处理架构实现方案
人工智能·spring boot·分布式·spring
毕设源码-钟学长3 小时前
【开题答辩全过程】以 基于Springboot的扶贫众筹平台为例,包含答辩的问题和答案
java·spring boot·后端
Java水解4 小时前
Spring Boot 4 升级指南:告别RestTemplate,拥抱现代HTTP客户端
spring boot·后端
神云瑟瑟4 小时前
spring boot拦截器获取requestBody的最佳实践
spring boot·拦截器·requestbody
暮色妖娆丶4 小时前
Spring 源码分析 BeanFactoryPostProcessor
spring boot·spring·源码
南极企鹅5 小时前
springBoot项目有几个端口
java·spring boot·后端
忧郁的Mr.Li6 小时前
SpringBoot中实现多数据源配置
java·spring boot·后端