项目地址: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的更多相关文章

  1. spring boot 2.0 集成 shiro 和 pac4j cas单点登录

    新开的项目,果断使用  spring boot  最新版本  2.0.3 ,免得后期升级坑太多,前期把雷先排了. 由于对 shiro 比较熟,故使用 shiro 来做权限控制.同时已经存在了 cas  ...

  2. Spring Boot 2.0 集成 Druid 数据源

    一.Maven项目依赖 <!-- 开发者工具(热部署 修改classpath下的文件springboot自动重启) --> <dependency> <groupId&g ...

  3. 7、Spring Boot 2.x 集成 Redis

    1.7 Spring Boot 2.x 集成 Redis 简介 继续上篇的MyBatis操作,详细介绍在Spring Boot中使用RedisCacheManager作为缓存管理器,集成业务于一体. ...

  4. Spring Boot 如何快速集成 Redis 哨兵?

    上一篇:Spring Boot 如何快速集成 Redis? 前面的分享栈长介绍了如何使用 Spring Boot 快速集成 Redis,上一篇是单机版,也有粉丝留言说有没有 Redis Sentine ...

  5. Spring Boot 2.0(八):Spring Boot 集成 Memcached

    Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站 ...

  6. spring boot 2.0.0 + shiro + redis实现前后端分离的项目

    简介 Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码学和会话管理.使用Shiro的易于理解的API,您可以快速.轻松地获得任何应用程序,从最小的移动应用程序到最大 ...

  7. springboot2.0(一):【重磅】Spring Boot 2.0权威发布

    就在昨天Spring Boot2.0.0.RELEASE正式发布,今天早上在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误, ...

  8. 业余草分享 Spring Boot 2.0 正式发布的新特性

    就在昨天Spring Boot2.0.0.RELEASE正式发布,今天早上在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误, ...

  9. Spring Boot 2.0 的快速入门(图文教程)

    摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! Spring Boot 2.0 的快速入门(图文教程) 大家都 ...

  10. 【重磅】Spring Boot 2.0权威发布

    新版本特性 新版本值得关注的亮点有哪些: 基于 Java 8,支持 Java 9 也就是说Spring Boot2.0的最低版本要求为JDK8,据了解国内大部分的互联网公司系统都还跑在JDK1.6/7 ...

随机推荐

  1. 百度网盘(百度云)SVIP超级会员共享账号每日更新(2023.12.2)

    一.百度网盘SVIP超级会员共享账号 可能很多人不懂这个共享账号是什么意思,小编在这里给大家做一下解答. 我们多知道百度网盘很大的用处就是类似U盘,不同的人把文件上传到百度网盘,别人可以直接下载,避免 ...

  2. TLS简单理解

    TLS简单理解 TLS的历史 From GTP3.5 TLS(传输层安全)是一种加密协议,旨在确保 Internet 通信的安全性和隐私保护.下面是 TLS 的历史概述: SSL(安全套接层):TLS ...

  3. [转帖]常用bash脚本功能

    https://cloud.tencent.com/developer/article/1906536 1.判断curl返回状态码 #!/bin/bash response=$(curl -sL -o ...

  4. [转帖]【SQL SERVER】锁机制

    https://www.cnblogs.com/WilsonPan/p/12618849.html   锁定是 SQL Server 数据库引擎用来同步多个用户同时对同一个数据块的访问的一种机制. 基 ...

  5. [转帖] mysql的timestamp会存在时区问题?

    我感觉 这样理解也有点不对 timestamp 应该是不带时区 只是 UTC1970-1-1 的时间戳 但是展示时会根据时区做一下计算 date time 就不会做转换而已.   原创:打码日记(微信 ...

  6. PG13 离线安装的简单办法

    1. 发现上班时间公司的网络几乎不可用 还是得找时间下载好离线包才可以. 找了一个最简单的办法 地址 https://yum.postgresql.org/ 选择版本 这次我选择最新的 继续之后继续选 ...

  7. 神经网络优化篇:详解为超参数选择合适的范围(Using an appropriate scale to pick hyperparameters)

    为超参数选择合适的范围 假设要选取隐藏单元的数量\(n^{[l]}\),假设,选取的取值范围是从50到100中某点,这种情况下,看到这条从50-100的数轴,可以随机在其取点,这是一个搜索特定超参数的 ...

  8. 解决跨域问题的8种方法,含网关、Nginx和SpringBoot~

    跨域问题是浏览器为了保护用户的信息安全,实施了同源策略(Same-Origin Policy),即只允许页面请求同源(相同协议.域名和端口)的资源,当 JavaScript 发起的请求跨越了同源策略, ...

  9. ClickHouse(06)ClickHouse建表语句DDL详细解析

    目录 当前服务器上创建表(单节点) 语法形式 使用显式架构 从相同结构的表复制创建 从表函数创建 从选择查询创建 分布式集群创建表 临时表 分区表 创建表语句关键字解析 空值或非空修饰符 默认值表达式 ...

  10. 微服务用yml安装系统(第一版)

    当用微服务安装系统后,面临服务较多,一个一个安装比较麻烦,是否有统一的脚本可以直接执行安装呢?答案是肯定的: 1.首先介绍一下所有安装脚本,如下图 spd-volume:是各服务外挂的资料卷 comm ...