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));
   
}
相关推荐
爱棋笑谦13 小时前
springboot—数据源相关配置
java·spring boot·spring
Spider Cat 蜘蛛猫21 小时前
Springboot SSO系统设计文档
java·spring boot·后端
学习3人组1 天前
业务主表+JSON自定义字段
java·spring boot·json
吕永强1 天前
基于SpringBoot+Vue宠物领养系统的设计与实现(源码+论文+部署)
spring boot·毕业设计·毕业论文·宠物领养·宠物领养系统
yoyo_zzm1 天前
PHP vs Java:后端语言终极选择指南
java·spring boot·后端·架构·php
鱼鳞_1 天前
苍穹外卖-Day01(开发环境搭建)
java·spring boot·spring·maven
学不思则罔1 天前
SpringBoot启动失败排查指南
spring boot·后端·部署
夕除1 天前
spring boot 5
数据库·spring boot·后端
yoyo_zzm1 天前
ThinkPHP1.X核心特性解析
数据库·spring boot·nginx
hexu_blog1 天前
前端vue后端java+springboot如何实现pdf,word,excel之间的相互转换
java·前端·vue.js·spring boot·文档转换