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));
   
}
相关推荐
Jaising6668 分钟前
Mybatis Plus 主键生成器实现思路分析
数据库·spring boot·mybatis
快乐就去敲代码@!31 分钟前
Boot Cache Star ⭐(高性能两级缓存系统)
spring boot·redis·后端·缓存·docker·压力测试
阿杆.1 小时前
如何在 Spring Boot 中接入 Amazon ElastiCache
java·spring boot·后端
Tjohn91 小时前
前后端分离项目(Vue-SpringBoot)迁移记录
前端·vue.js·spring boot
invicinble1 小时前
springboot的日志体系
java·spring boot·后端
阿拉斯攀登1 小时前
Spring Boot 自动配置的底层实现原理
spring boot·自动配置
czlczl200209251 小时前
拒绝 DTO 爆炸:详解 Spring Boot 参数校验中的“分组校验” (Validation Groups) 技巧
java·spring boot·后端
爱宇阳1 小时前
宝塔面板 + Nginx + Spring Boot 零停机滚动发布完整教程
运维·spring boot·nginx
小鸡脚来咯1 小时前
springboot项目包结构
java·spring boot·后端
爱学习的小可爱卢1 小时前
JavaEE进阶——SpringBoot日志从入门到精通
java·spring boot·后端