SpringBoot 配置 Redis 多缓存名(不同缓存名缓存失效时间不同)
import com.google.common.collect.ImmutableMap;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.Map;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate();
template.setConnectionFactory(factory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//配置使用FastJson进行序列化和反序列化操作
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
template.afterPropertiesSet();
//开启Redis事务
/**
* 为何要开启事务呢?redis本身是单线程执行的one by one
* 虽然都是原子性操作,那需要多个原子性的操作才算一个完整的事件呢
* 譬如 redis get set可能就是一对操作才能保证操作的完整性
* 譬如记录访问数 value 从0开始,在并发情况下多线程会同时查询到 value 为0 的情况,
* 此时两线程都得到value 0 为此都 +1操作 执行结果 value=1,而我们期望的结果至少是2才对
* 所以需要用事务来解决这一堆操作(get set)
*/
template.setEnableTransactionSupport(true);
return template;
}
@Bean
public CacheManager cacheManager(RedisTemplate<String, Object> template) {
//配置多个缓存名称 这里我们用个能用的模板 这里有坑点往下看
RedisCacheConfiguration templateRedisCacheCfg = RedisCacheConfiguration
.defaultCacheConfig()
// 设置key为String
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getStringSerializer()))
// 设置value 为自动转Json的Object
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getValueSerializer()))
// 不缓存null
.disableCachingNullValues();
//这里对RedisCacheConfiguration不熟悉的可能会有疑问,我们这样批量templateRedisCacheCfg.entryTtl(Duration.ofMinutes(15))最后不都是同一个引用吗,过期时间会生效吗?
Map<String, RedisCacheConfiguration> expires = ImmutableMap.<String, RedisCacheConfiguration>builder()
.put("15m", templateRedisCacheCfg.entryTtl(Duration.ofMinutes(15)))
.put("30m", templateRedisCacheCfg.entryTtl(Duration.ofMinutes(30)))
.put("60m", templateRedisCacheCfg.entryTtl(Duration.ofMinutes(60)))
.put("1d", templateRedisCacheCfg.entryTtl(Duration.ofDays(1)))
.put("30d", templateRedisCacheCfg.entryTtl(Duration.ofDays(30)))
.put("common-30d", templateRedisCacheCfg.entryTtl(Duration.ofDays(30)))
.build();
RedisCacheManager redisCacheManager =
RedisCacheManager.RedisCacheManagerBuilder
// Redis 连接工厂
.fromConnectionFactory(template.getConnectionFactory())
// 默认缓存配置
.cacheDefaults(templateRedisCacheCfg.entryTtl(Duration.ofHours(1)))
// 配置同步修改或删除 put/evict
.transactionAware()
.initialCacheNames(expires.keySet())
.withInitialCacheConfigurations(expires)
.build();
return redisCacheManager;
}
}
序列化类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName,SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullListAsEmpty).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
}
SpringBoot 配置 Redis 多缓存名(不同缓存名缓存失效时间不同)的更多相关文章
- springboot配置redis+jedis,支持基础redis,并实现jedis GEO地图功能
Springboot配置redis+jedis,已在项目中测试并成功运行,支持基础redis操作,并通过jedis做了redis GEO地图的java实现,GEO支持存储地理位置信息来实现诸如附近的人 ...
- SpringBoot配置redis和分布式session-redis
springboot项目 和传统项目 配置redis的区别,更加简单方便,在分布式系统中,解决sesssion共享问题,可以用spring session redis. 1.pom.xml <d ...
- SpringBoot 配置Redis
application.properties 文件内容 #Redis数据库索引(默认为0) spring.redis.database=0 #Redis服务器地址 spring.redis.host= ...
- springboot配置redis
https://www.cnblogs.com/xiaoping1993/p/7761123.html https://www.cnblogs.com/gdpuzxs/p/7222309.html s ...
- SpringBoot使用redis缓存List<Object>
一.概述 最近在做性能优化,之前有一个业务是这样实现的: 1.温度报警后第三方通讯管理机直接把报警信息保存到数据库 2.我们在数据库中添加触发器,(BEFORE INSERT)根据这条报警信息处理业务 ...
- springboot之Redis
1.springboot之Redis配置 在学习springboot配置Redis之前先了解Redis. 1.了解Redis Redis简介: redis是一个key-value存储系统.和Memca ...
- IDEA springboot配置
基于springboot2.1.7 springboot项目创建 springboot热部署 springboot配置swagger2 springboot配置mybatis springboot配置 ...
- Spring-Boot项目中配置redis注解缓存
Spring-Boot项目中配置redis注解缓存 在pom中添加redis缓存支持依赖 <dependency> <groupId>org.springframework.b ...
- springboot中redis做缓存时的配置
import com.google.common.collect.ImmutableMap;import org.slf4j.Logger;import org.slf4j.LoggerFactory ...
随机推荐
- MySQL中int(11)的意思
参考文献:https://segmentfault.com/a/1190000012479448 int(11)中的11代表的是字符的显示宽度,在字段类型为int时,无论你显示宽度设置为多少,int类 ...
- 题解【洛谷P1407】 [国家集训队]稳定婚姻
题面 题解 很好的\(Tarjan\)练习题. 主要讲一下如何建图. 先用\(STL \ map\)把每个人的名字映射成数字. 输入第\(i\)对夫妻时把女性映射成\(i\),把男性映射成\(i+n\ ...
- Cut Ribbon
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the follo ...
- Codeforces Round #525 (Div. 2) C. Ehab and a 2-operation task 数学 mod运算的性质
C. Ehab and a 2-operation task 数学 mod运算的性质 题意: 有两种对前缀的运算 1.对前缀每一个\(a +x\) 2.对前缀每一个\(a\mod(x)\) 其中x任选 ...
- Ultra-Thin LED Downlight Selection: 6 Things
LED Decorative Light Manufacturer description: ultra-thin LED downlight features can maintain the ...
- 【C语言】指针函数例子
#include<stdio.h> char* getword(char); char* getword(char c) { switch (c) { case'A':return&quo ...
- Verilog 编写规范
在学习Python时,作者有一句话对我影响很大.作者希望我们在学习编写程序的时候注意一些业内约定的规范.在内行人眼中,你的编写格式,就已经暴露了你的程度.学习verilog也是一样的道理,一段好的ve ...
- 【做题笔记】洛谷P1036 选数
作为一个 DFS 初学者这题真的做得很惨...其实窝学 DFS 一年多了,然后一开始就学不会最近被图论和数据结构打自闭后才准备好好学一学233 一开始,直接套框架,于是就有 #include < ...
- 利用数据结构排序的priority_queue
考虑以下几个问题: 将一个序列排序 某神仙: \(\mathtt{sort}\) !!! 每次取出最前面的两个数 某神仙: \(a_i\) 和 \(a_{i+1}\) 啊!! 相加,再加入序列 某神仙 ...
- at org.apache.hadoop.hbase.tmpl.master.BackupMasterStatusTmplImpl.renderNoFlush(BackupMasterStatusTm
at org.apache.hadoop.hbase.tmpl.master.BackupMasterStatusTmplImpl.renderNoFlush(BackupMasterStatusTm ...