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));
   
}
相关推荐
eggwyw18 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
韩立学长18 小时前
Springboot奶茶加盟信息管理系统m307m786(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
开longlong了吗?19 小时前
Luan Takeaway System:基于Spring Boot + Spring Cloud的外卖业务系统
spring boot·后端·spring cloud
刘 大 望20 小时前
SpringAI Tool Calling(工具调用)
java·spring boot·spring·ai·maven·intellij-idea·文心一言
dovens21 小时前
Spring Boot(快速上手)
java·spring boot·后端
旷世奇才李先生1 天前
065智慧农业专家远程指导系统-springboot+vue
java·vue.js·spring boot
zuoerjinshu1 天前
【SpringBoot】讲清楚日志文件&&lombok
java·spring boot·后端
jerryxiaosa1 天前
能源管理系统多设备对接时,业务层如何做到无感调用?ems4j 的实现思路
spring boot
李白的粉1 天前
基于springboot的论坛网站
java·spring boot·毕业设计·课程设计·论坛网站
Hvitur1 天前
eclipse新建SpringBoot项目
java·spring boot·eclipse