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 ...
随机推荐
- web-云部署上线
- [转帖]docker(一):docker pull指定运行平台架构
https://zhuanlan.zhihu.com/p/539888862 1.概述 大家好,我是欧阳方超.某日要在服务器上部署docker服务,其中要用到nginx,nginx经过pull.sav ...
- [转帖]vdbench - 性能压力测试工具
<存储工具系列文章>主要介绍存储相关的测试和调试工具,包括不限于dd.fio.vdbench.iozone.iometer.cosbench等性能负载工具,及strace等调试工具. 1. ...
- [转帖]Full GC (Ergonomics) 产生的原因
发生Full GC,有很多种原因,不仅仅是只有Allocation Failure. 还有以下这么多: #include "precompiled.hpp" #include &q ...
- 【转帖】Linux性能优化(十六)——中断绑定
一.中断绑定简介 1.中断简介 计算机中,中断是一种电信号,由硬件产生并直接送到中断控制器上,再由中断控制器向CPU发送中断信号,CPU检测到信号后,中断当前工作转而处理中断信号.CPU会通知操作系统 ...
- CDP技术系列(三):百万级QPS的人群命中服务接口性能优化指南
一.背景介绍 CDP系统提供了强大的标签和群体的构建能力,面对海量数据的标签和群体,我们采用了Bitmap+ClickHouse的存储与计算方案.详细内容可以参考之前文章. 有了群体之后,它们被广泛的 ...
- 02uni-app v-for循环列表 v-if的使用
onLoad onShow onHide函数的使用## 这三个函数的使用 // 监听页面的加载 参数e是上一个页面传递过来的参数 参数是一个对象 如果没有为空{} onLoad(e) { consol ...
- 【scikit-learn基础】--『回归模型评估』之可视化评估
在scikit-learn中,回归模型的可视化评估是一个重要环节.它帮助我们理解模型的性能,分析模型的预测能力,以及检查模型是否存在潜在的问题.通过可视化评估,我们可以更直观地了解回归模型的效果,而不 ...
- 【小实验】使用 wrk 的 docker 容器来压测另一个容器
作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 GET 请求 想压测容器环境的服务性能,发现两个麻烦: 本 ...
- Go 匿名函数与闭包
Go 匿名函数与闭包 匿名函数和闭包是一些编程语言中的重要概念,它们在Go语言中也有重要的应用.让我们来详细介绍这两个概念,并提供示例代码来帮助理解. 目录 Go 匿名函数与闭包 一.匿名函数(Ano ...