当前位置: 首页 > news >正文

Springboot统一给redis缓存的Key加前缀

第一步:配置redis

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:"; @Beanpublic 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() {@Overridepublic byte[] prefix(String key) {return (redisPrefix + ":" + key).getBytes();}};template.setKeyGenerator(keyPrefix);return template;}
}

第二步:在使用

//在代码中注入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));}


http://www.mrgr.cn/news/8009.html

相关文章:

  • 【网络】传输层协议——TCP协议(初阶)
  • Java JNA调用C函数常见问题及解决方法
  • Elasticsearch核心
  • 开发者学习类网站
  • 第二课《动态规划》
  • Swift 可选链
  • 区块链的搭建与运维4
  • 芯片后端之 PT 使用 report_timing 产生报告 之 常用命令
  • adb install
  • 火语言RPA流程组件介绍--获取/结束进程
  • 2.2 python基础知识复习——python面向对象的原理和代码详解
  • Nginx 405 not allowed
  • 代码随想录算法训练营第55天| 并查集 107.寻找存在的路径
  • 开发团队学会应对突发的技术故障和危机
  • Rust 学习笔记 2:猜数字游戏
  • 【Linux篇】vim编译器
  • 仿Muduo库实现高并发服务器——EventLoop模块
  • mysql和oracle函数比较
  • Go语言Time包的使用
  • 深入浅出消息队列----【Broker 集群】