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));
   
}
相关推荐
飘零未归人4 分钟前
SpringBoot 整合mongoDB并自定义连接池,实现多数据源配置
spring boot·后端·mongodb
howard20051 小时前
1.2.2 使用Maven方式构建Spring Boot项目
spring boot·maven方式构建
浅念同学1 小时前
JavaWeb-Servlet对象生命周期
java·网络·spring boot·servlet·java-ee·tomcat
Dyan_csdn1 小时前
【Java项目】基于Spring Boot的简历系统
java·数据库·spring boot·spring·tomcat
web_132334214361 小时前
Spring Boot+Vue项目从零入手
vue.js·spring boot·后端
web_155342746562 小时前
Spring Boot(十六):使用 Jenkins 部署 Spring Boot
spring boot·后端·jenkins
m0_748245172 小时前
Spring Boot项目开发常见问题及解决方案(上)
java·spring boot·后端
今天的接口写完了吗?2 小时前
Spring Boot操作MaxComputer(保姆级教程)
java·spring boot·后端
m0_748248773 小时前
Spring Boot 3.x 引入springdoc-openapi (内置Swagger UI、webmvc-api)
spring boot·后端·ui
大溪地C3 小时前
Spring Boot 整合 Spring MVC /(整合Web)笔记
spring boot·spring·mvc