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));
   
}
相关推荐
骆晨学长几秒前
基于springboot学生健康管理系统的设计与实现
java·开发语言·spring boot·后端·spring
骆晨学长几秒前
基于Springboot的医疗健康助手开题报告
java·spring boot·后端
if时光重来2 分钟前
springboot项目实现导出excel动态设置表头
spring boot·后端·excel
code.song3 分钟前
校园社团|基于springBoot的校园社团信息管理系统设计与实现(附项目源码+论文+数据库)
数据库·spring boot·后端
code.song9 分钟前
医疗报销|基于springBoot的医疗报销系统设计与实现(附项目源码+论文+数据库)
数据库·spring boot·后端
wxin_VXbishe2 小时前
springboot瑜伽课约课小程序-计算机毕业设计源码87936
java·c++·spring boot·python·spring·servlet·php
2401_854391082 小时前
旅游网站设计与实现:SpringBoot技术手册
spring boot·后端·旅游
小扳2 小时前
Redis 篇-初步了解 Redis 持久化、Redis 主从集群、Redis 哨兵集群、Redis 分片集群
java·spring boot·redis·分布式·缓存
灯火不休ᝰ2 小时前
7--SpringBoot-后端开发、原理
java·spring boot·spring
抚月code3 小时前
SpringBoot基础
java·spring boot·后端