Springboot2.x使用redis作为缓存
一、Springboot2.x关于配置redis作为缓存。
基本配置如下:
(1)在application.properties文件中
spring.redis.database=2 //第几个数据库,由于redis中数据库不止一个 spring.redis.host=localhost // 也可指定为127.0.0.1 spring.redis.port=6379 // 默认端口 spring.redis.password= // 默认为空 # springboot2.x以上如此配置,由于2.x的客户端是lettuce# 单位要带上 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.min-idle=0 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.max-wait=10000ms spring.redis.lettuce.shutdown-timeout=100ms# springboot1.x如此配置,由于1.x的客户端是jedis #spring.redis.jedis.pool.max-active=8 #spring.redis.jedis.pool.min-idle=0 #spring.redis.jedis.pool.max-idle=8 #spring.redis.jedis.pool.max-wait=-1 #spring.redis.timeout=500
(2)在pom.xml中
<!--spring2.0集成redis所需common-pool2--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.4.2</version></dependency> <!-- redis依赖,2.0以上使用这个依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency> <!-- 缓存依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>
(3)自定义缓存管理器RedisCacheConfig
package com.xf.spring_test.config;import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; 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.RedisConnectionFactory; import org.springframework.data.redis.serializer.*;import java.time.Duration;@Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport {private static final Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class);// 自定义key生成器 @Beanpublic KeyGenerator keyGenerator(){return (o, method, params) ->{StringBuilder sb = new StringBuilder();sb.append(o.getClass().getName()); // 类目sb.append(method.getName()); // 方法名for(Object param: params){sb.append(param.toString()); // 参数名 }return sb.toString();};}// 配置缓存管理器 @Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(60)) // 60s缓存失效// 设置key的序列化方式 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))// 设置value的序列化方式 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))// 不缓存null值 .disableCachingNullValues();RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).cacheDefaults(config).transactionAware().build();logger.info("自定义RedisCacheManager加载完成");return redisCacheManager;}/* @Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);redisTemplate.setKeySerializer(keySerializer());redisTemplate.setHashKeySerializer(keySerializer());redisTemplate.setValueSerializer(valueSerializer());redisTemplate.setHashValueSerializer(valueSerializer());logger.info("序列化完成!");return redisTemplate;}*/// key键序列化方式private RedisSerializer<String> keySerializer() {return new StringRedisSerializer();}// value值序列化方式private GenericJackson2JsonRedisSerializer valueSerializer(){return new GenericJackson2JsonRedisSerializer();} }
(4)在service的实现类中加入需要的注解,即可实现缓存数据
package com.xf.spring_test.service.impl;import com.xf.spring_test.dao.PersonDao; import com.xf.spring_test.domain.Person; import com.xf.spring_test.service.UserService; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service;import java.util.List;@Service public class UserServiceImpl implements UserService {PersonDao personDao;public UserServiceImpl(PersonDao personDao) {this.personDao = personDao;}@Override@Cacheable(cacheNames = "user")public Person getUserById(Integer id) {return personDao.getUserById(id);}@Override@Cacheable(cacheNames = "users")public List<Person> getAllUser() {return personDao.getAllUser();}@Override@CachePut(cacheNames = "updateUser", condition = "#person!=null", unless = "#result>0")public Integer editUser(Person person) {return personDao.editUser(person);}@Override@CacheEvict(cacheNames = "delUser", allEntries = true, beforeInvocation = true,condition = "#userId>0")public Integer delUser(Integer userId) {return personDao.delUser(userId);} }
二、注意事项
(1)要缓存的JAVA对象必须实现Serailizable接口
(2)必须要配置RedisCacheManager 来管理缓存
转载于:https://www.cnblogs.com/crazy-xf/p/10483180.html
Springboot2.x使用redis作为缓存相关推荐
- SpringBoot2.x整合Redis实战 4节课
1.分布式缓存Redis介绍 简介:讲解为什么要用缓存和介绍什么是Redis,新手练习工具 1.redis官网 https://redis.io/download 2.新 ...
- SpringBoot2.x整合redis实战讲解
SpringBoot2.x整合redis实战讲解 简介:使用springboot-starter整合reids实战 1.官网:https://docs.spring.io/spring-boot/do ...
- springboot2.x 的 RedisCacheManager设置缓存失效时间
由于最近项目中需要使用redis做缓存并修改其失效时间,使用的是springboot2.x来搭建的项目. 看了看网上的一些教程,但是大多数教程都是基于1.x的版本来讲解的,但是springboot2 ...
- SpringBoot2.0整合Redis实战
SpringBoot2.x整合Redis实战 1.分布式缓存Redis介绍 简介:讲解为什么要用缓存和介绍什么是Redis,新手练习工具 1.redis官网 https://redis.io/down ...
- Springboot整合redis实现缓存及其缓存运行原理浅析
声明:小白,学习阶段,主要目的是为了记录学习过程,本文仅供参考,如有不足的地方欢迎指出讨论交流 本文基于Springboot2.1.3版本开发: 准备阶段 首先是pom.xml文件所需的依赖: < ...
- Spring Boot 整合Redis 实现缓存
本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解 运行环境 ...
- 项目总结10:通过反射解决springboot环境下从redis取缓存进行转换时出现ClassCastException异常问题...
通过反射解决springboot环境下从redis取缓存进行转换时出现ClassCastException异常问题 关键字 springboot热部署 ClassCastException异常 反射 ...
- redis一般缓存什么样数据_门户数据展示_Redis缓存数据
学习主题:门户数据展示_Redis缓存数据 一.Redis_3主3从集群环境搭建 谈单你对读写分离和主从同步的理解 读写分离:Master负责写数据的操作,salve负责读数据的操作 主从同步:sal ...
- SpringBoot2.0配置redis相关
2019独角兽企业重金招聘Python工程师标准>>> SpringBoot2.0中redis的配置 REDIS (RedisProperties) Redis数据库索引(默认为0) ...
最新文章
- 基于交换技术的网络中,全双工主要运行在?( 内有答案与详解)
- R假设检验之Breusch-Pagan检验(Breusch-Pagan Test)
- DL之Mask R-CNN:2018.6.26世界杯阿根廷队VS尼日利亚比赛2:1实现Mask R-CNN目标检测
- php 生成缩略图保存,PHP批量生成图片缩略图的方法
- 当初怼刘海屏最狠的三星,为什么又用了回来?
- Flex 传JAVA BEAN 到后台 JAVA
- X86汇编语言从实模式到保护模式13:保护模式程序的动态加载和执行
- 关于表格前面checkbox复选框不打勾的问题
- Java语言中的----继承(二)
- AMD IOMMU与Linux (4) -- Domain, Group, Device
- WPS简历模板的图标怎么修改_个人简历模板集锦,简历自我评价怎么写?
- 人工神经网络算法有哪些,人工神经网络算法优点
- 字面量long后面的大小写l
- 怎么识别伪装IP的网络攻击
- VEH(向量化异常处理)
- Android JetPack底部导航Navigation 组件的介绍与使用
- PS色彩算法理解记录 4 Screen
- 小米、360、萤石等智能摄像头如何选购?需要注意哪些功能信息
- JS处理JSON字符串转数组,数字超17为处理方法
- 到底什么是牛逼?什么是傻逼?什么又是装逼?NB,SB,ZB
热门文章
- 2d游戏地图编辑器_从零开始的unity(3)——2d背景的制作和使用
- 收藏 | 卷积神经网络中十大拍案叫绝的操作
- Python中sorted()函数的高级用法详解
- java 火星坐标转wgs84_js中火星坐标、百度坐标、WGS84坐标转换实现方法示例
- 数学建模之图论——图与网络模型(一)(基本概念和最短路问题,附MATLAB源码)
- Tensorflow教程: tf.Variable() 和tf.get_variable()
- 关于numpy mean函数的axis参数
- 可解释性与deep learning的发展
- Matlab线性/非线性规划优化算法(1)
- 04732微型计算机技术,04732微型计算机及其接口技术200710