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 多缓存名(不同缓存名缓存失效时间不同)的更多相关文章

  1. springboot配置redis+jedis,支持基础redis,并实现jedis GEO地图功能

    Springboot配置redis+jedis,已在项目中测试并成功运行,支持基础redis操作,并通过jedis做了redis GEO地图的java实现,GEO支持存储地理位置信息来实现诸如附近的人 ...

  2. SpringBoot配置redis和分布式session-redis

    springboot项目 和传统项目 配置redis的区别,更加简单方便,在分布式系统中,解决sesssion共享问题,可以用spring session redis. 1.pom.xml <d ...

  3. SpringBoot 配置Redis

    application.properties 文件内容 #Redis数据库索引(默认为0) spring.redis.database=0 #Redis服务器地址 spring.redis.host= ...

  4. springboot配置redis

    https://www.cnblogs.com/xiaoping1993/p/7761123.html https://www.cnblogs.com/gdpuzxs/p/7222309.html s ...

  5. SpringBoot使用redis缓存List<Object>

    一.概述 最近在做性能优化,之前有一个业务是这样实现的: 1.温度报警后第三方通讯管理机直接把报警信息保存到数据库 2.我们在数据库中添加触发器,(BEFORE INSERT)根据这条报警信息处理业务 ...

  6. springboot之Redis

    1.springboot之Redis配置 在学习springboot配置Redis之前先了解Redis. 1.了解Redis Redis简介: redis是一个key-value存储系统.和Memca ...

  7. IDEA springboot配置

    基于springboot2.1.7 springboot项目创建 springboot热部署 springboot配置swagger2 springboot配置mybatis springboot配置 ...

  8. Spring-Boot项目中配置redis注解缓存

    Spring-Boot项目中配置redis注解缓存 在pom中添加redis缓存支持依赖 <dependency> <groupId>org.springframework.b ...

  9. springboot中redis做缓存时的配置

    import com.google.common.collect.ImmutableMap;import org.slf4j.Logger;import org.slf4j.LoggerFactory ...

随机推荐

  1. Vue中import '@...'的意思

    转载: https://blog.csdn.net/xiazeqiang2018/article/details/81325996 写项目的时候看到很多导入都是@开头,这是webpack的路径别名,相 ...

  2. python之路之生成器和的迭代器

    生成器的基本原理 生成器实现xrange 迭代器

  3. Pikachu练习平台(暴力破解)

    Pikachu练习平台(暴力破解) 因为下面要用到burp suite,这里先简单介绍一下intruder模块的东西 Target选项:        设置攻击目标,可以通过proxy发送 Pasit ...

  4. DVWA全级别之Insecure CAPTCHA(不安全的验证码)

    Insecure CAPTCHA Insecure CAPTCHA,意思是不安全的验证码,CAPTCHA是Completely Automated Public Turing Test to Tell ...

  5. Android开发实战——记账本(2)

    开发日志(2)——Bean目录以及数据库 首先编写一些自己生成的数据进行测试,看一下能否显示在模拟器上.那前提就是先写出bean目录,这和之前学的Javaweb步骤差不多.bean目录有三个变量事件. ...

  6. ansible笔记(7):常用模块之包管理模块

    1.yum_repository模块 用于远程管理远程主机上的yum仓库. 参数解析: name:必须参数,用于指定要操作的唯一的仓库ID,也就是.repo配置文件中每个仓库对应的“中括号”内的仓库I ...

  7. 程序员必需知道的Chrome使用技巧(入门篇)

    浏览器版本 Chrome Canary 新增一些没有经过Google工程师的测试或使用的浏览器功能版本.Chrome Dev让大多数开发人员主要使用此版本来测试对浏览器的重大版本功能版本.Chrome ...

  8. JavaScript arguments对象浅析

    arguments对象 概念 用法 属性 arguments对象 概念 arguments 是一个类数组对象.代表传给一个function的参数列表. 用法 function a() { consol ...

  9. drf框架,restful接口规范,源码分析

    复习 """ 1.vue如果控制html 在html中设置挂载点.导入vue.js环境.创建Vue对象与挂载点绑定 2.vue是渐进式js框架 3.vue指令 {{ }} ...

  10. Codeforces Round #624 (Div. 3) D. Three Integers

    You are given three integers a≤b≤ca≤b≤c . In one move, you can add +1+1 or −1−1 to any of these inte ...