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 ...
随机推荐
- JVM的GC学习
JVM的GC学习 2023-12-28T17:20:25.182+0800: 7.363: [Full GC (Metadata GC Threshold) [PSYoungGen: 29067K-& ...
- [转帖]tiup cluster reload
https://docs.pingcap.com/zh/tidb/stable/tiup-component-cluster-reload 4 Contributors 在修改集群配置之后,需要通过 ...
- JVM启动速度大页内存验证
大页内存设置 先查看 cat /proc/meminfo |grep -i huge 获取大页内存的大小信息. AnonHugePages: 42022912 kB HugePages_Total: ...
- Redis-dump Docker搭建的快速指南
背景 最近学习redis想能够将dump文件进行导入处理. 看到比较好的办法都是使用ruby ,但是公司的网络太感人了. 想着比较简单的办法是通过docker方式来搭建. 这里简单记录一下搭建过程. ...
- 海量数据 vastbase G100 V2.2安装简单总结
海量数据vastbase G100 V2.2 安装总结 背景说明 最近进行信创四期的数据库兼容性验证, 获取了海量数据的一个信创名录内的安装介质. 一直忙于出差, 今天晚上趁着冬至回家比较早在家里进行 ...
- [译]深入了解现代web浏览器(二)
本文是根据Mariko Kosaka在谷歌开发者网站上的系列文章https://developer.chrome.com/blog/inside-browser-part2/ 翻译而来,共有四篇,该篇 ...
- 【JS 逆向百例】当乐网登录接口参数逆向
声明 本文章中所有内容仅供学习交流,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关,若有侵权,请联系我立即删除! 逆向目标 目标:当乐网登录 主页:https://oauth.d.cn ...
- TienChin 渠道管理-渠道导出
ChannelController /** * 导出渠道列表 */ @PreAuthorize("hasPermission('tienchin:channel:export')" ...
- springboot集成swagger之knife4j实战(升级版)
官方文档链接:https://doc.xiaominfo.com/ 一.Knifej和swagger-bootstrap-ui对比 Knife4j在更名之前,原来的名称是叫swagger-bootst ...
- C# 使用正则表达式
在C#中,可以使用正则表达式来处理文本字符串.正则表达式是一种特殊的文本模式,用于匹配和搜索字符串.它可以识别特定模式,如邮箱地址.电话号码.网址等.正则表达式是C#中常用的一种文本处理技术,使用它可 ...