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 ...
随机推荐
- Cloudquery的学习安装与使用
Cloudquery的学习安装与使用 下载 官方下载地址: https://www.cloudquery.club/download https://pan.baidu.com/s/1a7XOrnMU ...
- [转帖]SSH交互式脚本StrictHostKeyChecking选项 benchmode=yes
https://www.cnblogs.com/klb561/p/11013774.html SSH 公钥检查是一个重要的安全机制,可以防范中间人劫持等黑客攻击.但是在特定情况下,严格的 SSH 公钥 ...
- [转帖]AMD Zen CPU 架构以及不同CPU性能大PK
https://plantegg.github.io/2021/08/13/AMD_Zen_CPU%E6%9E%B6%E6%9E%84/ 前言 本文先介绍AMD Zen 架构,结合前一篇文章<C ...
- [转帖]VMware ESXi 各版本号对照表
本博文转自以下链接: VMware ESXi Release and Build Number History | virten.net vSphere ESXi 7.0 Name Patch Dat ...
- [转帖]巧用 Docker Buildx 构建多种系统架构镜像
http://www.taodudu.cc/news/show-4511396.html?action=onClick Docker Buildx 是一个 Docker CLI 插件,其扩展了 Doc ...
- [转帖]使用Linux命令快速查看某一行
原创:打码日记(微信公众号ID:codelogs),欢迎分享,转载请保留出处. 简介# 当年,我还是Linux菜鸟的时候,就在简历上写着精通Linux命令了,而当面试官问我"如何快速查看 ...
- Nginx 大并发 调优设置
为了性能测试,放弃部分功能,保证绝对性能. 注意可能不能用于生产环境. 下面开始简单讲解. 1. worker_processes 工作线程数. 发现不用太多 一定不能多于操作系统的CPU核数. 2. ...
- RN 表单TextInput的用法
你要注意安卓和苹果是不同的哈 有些属性是苹果才有的,有些是安卓独有的 有些两个都有哈 // 边框要设置两个属性哈 borderColor: 'pink', marginTop: 10, 具体看地址 h ...
- 时不我待,拥抱趋势,开源IM项目OpenIM技术简介
坚持开源 开源的理念是基于共享.合作和透明的原则,将软件.代码等知识资源公开并允许他人使用.修改和重新分发,以促进创新和发展.以下是几个开源的优点: 创新:开源可以促进创新,通过让其他人改进或扩展已有 ...
- 使用svn.externals(外链)提升美术多个svn目录的svn up速度
svn up多个目录耗时大 svn上的美术资源项目,在打包机上对一个很久没有变化的目录进行svn up也是需要消耗不少时间的,特别打包时需要对多个目录进行svn up,比如空跑54个目录的svn up ...