spring boot 2.0集成并使用redis
项目地址:https://gitee.com/indexman/spring_boot_in_action
前面一章介绍了spring boot自带的缓存,下面讲一下如何在2.0版本中集成并使用redis进行数据缓存。
1.修改pom.xml添加redis依赖
<!--引入redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.修改application.yml添加redis服务器配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root123
url: jdbc:mysql://localhost:3306/spring_cache?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT&useSSL=false
redis:
host: 192.168.43.123
port: 6379
mybatis:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
debug: true
3.编写测试方法
package com.laoxu.springboot;
import com.laoxu.springboot.bean.Employee;
import com.laoxu.springboot.mapper.EmployeeMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleCacheApplicationTests {
@Autowired
EmployeeMapper employeeMapper;
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
RedisTemplate redisTemplate;
//注入自定义RedisTemplate
@Autowired
// RedisTemplate<Object,Employee> myRedisTemplate;
@Test
public void test01(){
stringRedisTemplate.opsForValue().append("msg","Hello World!");
String msg = stringRedisTemplate.opsForValue().get("msg");
System.out.println(msg);
}
//测试保存Employee对象
@Test
public void testSaveEmp(){
Employee emp = employeeMapper.getEmpById(1);
//默认保存对象使用的jdk序列化
redisTemplate.opsForValue().set("emp01", emp);
//使用自定义JSON序列化器
//myRedisTemplate.opsForValue().set("emp01", emp);
}
@Test
public void contextLoads() {
Employee emp = employeeMapper.getEmpById(1);
System.out.println(emp);
}
}
4.运行测试查看效果

一看存的怎么是16进制,完全看不懂有木有? 我们要的最好是JSON。那咋整?看第5步。

5.添加自定义redis配置
包括了自定义CacheManager, RedisTemplate, StringRedisTemplate
package com.laoxu.springboot.config;
import com.laoxu.springboot.util.FastJsonRedisSerializer;
import jdk.nashorn.internal.runtime.logging.Logger;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* 自定义redis配置
* @author xusucheng
* @create 2019-01-28
**/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {
private Duration timeToLive = Duration.ZERO;
public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive;
}
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(this.timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
.disableCachingNullValues();
RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.transactionAware()
.build();
System.out.println("自定义RedisCacheManager加载完成");
return redisCacheManager;
}
@Bean
//@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
//使用fastjson序列化
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
System.out.println("自定义RedisTemplate加载完毕!");
return template;
}
@Bean
//@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
System.out.println("自定义StringRedisTemplate加载完毕!");
return template;
}
private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
}
private RedisSerializer<Object> valueSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
}
6.再次运行测试方法
艾玛,这下总算好了,看着也舒服是吧。

7.不要忘了再测试下前一章写的emp控制器
就是验证一下缓存在redis下是否好使,之前那些操作是否正常呗。
艾玛,21点了。赶紧下班,快赶不上531路公交了。。。
spring boot 2.0集成并使用redis的更多相关文章
- spring boot 2.0 集成 shiro 和 pac4j cas单点登录
新开的项目,果断使用 spring boot 最新版本 2.0.3 ,免得后期升级坑太多,前期把雷先排了. 由于对 shiro 比较熟,故使用 shiro 来做权限控制.同时已经存在了 cas ...
- Spring Boot 2.0 集成 Druid 数据源
一.Maven项目依赖 <!-- 开发者工具(热部署 修改classpath下的文件springboot自动重启) --> <dependency> <groupId&g ...
- 7、Spring Boot 2.x 集成 Redis
1.7 Spring Boot 2.x 集成 Redis 简介 继续上篇的MyBatis操作,详细介绍在Spring Boot中使用RedisCacheManager作为缓存管理器,集成业务于一体. ...
- Spring Boot 如何快速集成 Redis 哨兵?
上一篇:Spring Boot 如何快速集成 Redis? 前面的分享栈长介绍了如何使用 Spring Boot 快速集成 Redis,上一篇是单机版,也有粉丝留言说有没有 Redis Sentine ...
- Spring Boot 2.0(八):Spring Boot 集成 Memcached
Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站 ...
- spring boot 2.0.0 + shiro + redis实现前后端分离的项目
简介 Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码学和会话管理.使用Shiro的易于理解的API,您可以快速.轻松地获得任何应用程序,从最小的移动应用程序到最大 ...
- springboot2.0(一):【重磅】Spring Boot 2.0权威发布
就在昨天Spring Boot2.0.0.RELEASE正式发布,今天早上在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误, ...
- 业余草分享 Spring Boot 2.0 正式发布的新特性
就在昨天Spring Boot2.0.0.RELEASE正式发布,今天早上在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误, ...
- Spring Boot 2.0 的快速入门(图文教程)
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! Spring Boot 2.0 的快速入门(图文教程) 大家都 ...
- 【重磅】Spring Boot 2.0权威发布
新版本特性 新版本值得关注的亮点有哪些: 基于 Java 8,支持 Java 9 也就是说Spring Boot2.0的最低版本要求为JDK8,据了解国内大部分的互联网公司系统都还跑在JDK1.6/7 ...
随机推荐
- Linux-磁盘-di-目录查询-du-tree
- [转帖]Oracle数据库中ITL详解
首先说明这篇文章是转载的,原文地址:http://blog.sina.com.cn/s/blog_616b428f0100lwvq.html 1.什么是ITL ITL(Interested Trans ...
- [转帖]CENTOS6.5 没有/LIB64/LIBFUSE.SO.2的问题
yum install fuse-libs
- 【转帖】Linux中如何取消ln链接?(linuxln取消)
https://www.dbs724.com/163754.html Linux系统使用ln命令可以快速创建链接,ln链接是指把文件和目录链接起来,当改变源时可以快速地改变整个目录下的文件和目录.有时 ...
- [转帖]自动化回归测试工具 —— AREX 上手实践
https://my.oschina.net/arextest/blog/8589156 AREX 是一款开源的自动化测试工具平台,基于 Java Agent 技术与比对技术,通过流量录制回放能力 ...
- CentOS创建vsftp进行读写操作的简单方法
1. 安装vsftpd yum install epel-release yum install vsftpd 2. 进入系统设置简单进行处理 注意 user_list 是不允许访问的列表. [roo ...
- 【计算几何,数学】7.14 T3 @ xdfz
Problem Link 给定 \(n\) 个球和一个点 \(P\),求点 \(P\) 到这些球的交内一点的距离的最小值.保证有解.\(n\le 10^6\). 和最小圆覆盖一个套路.考虑维护一个当前 ...
- React中受控组件与非受控组件的使用
受控组件 受控组件的步骤: 1.在state中添加一个状态,作为表单元素的value值(控制表单元素值的来源) 2.给表单元素绑定change事件,将表单元素的值设置为state的值(这样就可以控制表 ...
- 限制input框中字数的输入maxlength
今天产品提出一个需求就是.限制input框中的的值. 当用户超过10个字符时,用户再次输入的时,就不能够输入了. (最后就能够输入10个字符) maxlength=10 <input maxle ...
- Qt中qreal的坑
今天在写Qt的时候遇到了一个bug:同样一个方程在PC机上算的结果是11,但在arm-Linux设备上算出来的结果是12,我自己用计算器按出来的结果也是12. 该段程序是这样的: maxnumbar ...