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));
   
}
相关推荐
云创智城-yuncitys11 小时前
YunParking 4.0:JDK 17 与 Spring Boot 3.2 的停车云升级
java·开发语言·spring boot
paopaokaka_luck13 小时前
灾害应急物资管理系统(AI应急助手、Echarts可视化数据看板、捐赠入库联动、 物资全流程管理、库存变动追溯、灾情资讯与互动反馈、物资发放公示)
java·前端·javascript·spring boot·mysql·tomcat·echarts
学长毕设15 小时前
基于SpringBoot的网上流浪狗救助捐赠平台-附源码
java·spring boot·后端
码农的日常15 小时前
前后端Long精度丢失的踩坑
spring boot·架构
杨运交16 小时前
086-对象存储模块-基于Spring Boot的文件存储模块监控设计与实现
java·spring boot·后端
wifi___18 小时前
SpringBoot自动装配原理
java·spring boot·后端
Small-Young18 小时前
数据库乐观锁深度解析:MySQL、PostgreSQL 实战 + Spring Boot 集成指南
数据库·spring boot·mysql·postgresql·乐观锁·并发控制
她的男孩19 小时前
租户 A 的验证码,却用了租户 B 的 AccessKey:Forge Admin 修跨租户短信串发
java·spring boot·saas
小蒜学长20 小时前
基于SpringBoot+Vue的云南地区扶贫助农系统的设计与实现(代码+数据库+LW)
java·vue.js·spring boot·后端·乡村振兴
RuoyiOffice20 小时前
Hyper-V+Kubernetes 搭建实战:保留 Windows,构建三节点 Linux 容器集群
linux·spring boot·kubernetes·containerd·hyper-v·微服务部署·ruoyi office