Spring Boot 整合 Redis 实现缓存操作
一、缓存的应用场景
二、更新缓存的策略

三、运行 springboot-mybatis-redis 工程案例
1
|
CREATE DATABASE springbootdb; |
1
2
3
4
5
6
7
8
|
DROP TABLE IF EXISTS `city`; CREATE TABLE `city` ( ` id ` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '城市编号' , `province_id` int(10) unsigned NOT NULL COMMENT '省份编号' , `city_name` varchar(25) DEFAULT NULL COMMENT '城市名称' , `description` varchar(25) DEFAULT NULL COMMENT '描述' , PRIMARY KEY (` id `) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; |
1
|
INSERT city VALUES (1 ,1, '温岭市' , 'BYSocket 的家在温岭。' ); |
1
2
3
4
5
6
7
|
springboot-mybatis-redis 工程项目结构如下图所示: org.spring.springboot.controller - Controller 层 org.spring.springboot.dao - 数据操作层 DAO org.spring.springboot.domain - 实体类 org.spring.springboot.service - 业务逻辑层 Application - 应用启动类 application.properties - 应用配置文件,应用启动会自动读取配置 |
1
|
mvn clean install |
1
2
|
2017-04-13 18:29:00.273 INFO 13038 --- [nio-8080- exec -1] o.s.s.service.impl.CityServiceImpl : CityServiceImpl.findCityById() : 城市插入缓存 >> City{ id =12, provinceId=3, cityName= '三亚' , description= '水好,天蓝' } 2017-04-13 18:29:03.145 INFO 13038 --- [nio-8080- exec -2] o.s.s.service.impl.CityServiceImpl : CityServiceImpl.findCityById() : 从缓存中获取了城市 >> City{ id =12, provinceId=3, cityName= '三亚' , description= '水好,天蓝' } |
1
|
2017-04-13 18:29:52.248 INFO 13038 --- [nio-8080- exec -9] o.s.s.service.impl.CityServiceImpl : CityServiceImpl.deleteCity() : 从缓存中删除城市 ID >> 12 |
四、springboot-mybatis-redis 工程代码配置详解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
<?xml version= "1.0" encoding= "UTF-8" ?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion>4.0.0< /modelVersion > <groupId>springboot< /groupId > <artifactId>springboot-mybatis-redis< /artifactId > <version>0.0.1-SNAPSHOT< /version > <name>springboot-mybatis-redis :: 整合 Mybatis 并使用 Redis 作为缓存< /name > <!-- Spring Boot 启动父依赖 --> <parent> <groupId>org.springframework.boot< /groupId > <artifactId>spring-boot-starter-parent< /artifactId > <version>1.5.1.RELEASE< /version > < /parent > <properties> <mybatis-spring-boot>1.2.0< /mybatis-spring-boot > <mysql-connector>5.1.39< /mysql-connector > <spring-boot-starter-redis-version>1.3.2.RELEASE< /spring-boot-starter-redis-version > < /properties > <dependencies> <!-- Spring Boot Reids 依赖 --> <dependency> <groupId>org.springframework.boot< /groupId > <artifactId>spring-boot-starter-redis< /artifactId > <version>${spring-boot-starter-redis-version}< /version > < /dependency > <!-- Spring Boot Web 依赖 --> <dependency> <groupId>org.springframework.boot< /groupId > <artifactId>spring-boot-starter-web< /artifactId > < /dependency > <!-- Spring Boot Test 依赖 --> <dependency> <groupId>org.springframework.boot< /groupId > <artifactId>spring-boot-starter- test < /artifactId > <scope> test < /scope > < /dependency > <!-- Spring Boot Mybatis 依赖 --> <dependency> <groupId>org.mybatis.spring.boot< /groupId > <artifactId>mybatis-spring-boot-starter< /artifactId > <version>${mybatis-spring-boot}< /version > < /dependency > <!-- MySQL 连接驱动依赖 --> <dependency> <groupId>mysql< /groupId > <artifactId>mysql-connector-java< /artifactId > <version>${mysql-connector}< /version > < /dependency > <!-- Junit --> <dependency> <groupId>junit< /groupId > <artifactId>junit< /artifactId > <version>4.12< /version > < /dependency > < /dependencies > < /project > |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
## 数据源配置 spring.datasource.url=jdbc:mysql: //localhost :3306 /springbootdb ?useUnicode= true &characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ## Mybatis 配置 mybatis.typeAliasesPackage=org.spring.springboot.domain mybatis.mapperLocations=classpath:mapper/*.xml ## Redis 配置 ## Redis数据库索引(默认为0) spring.redis.database=0 ## Redis服务器地址 spring.redis.host=127.0.0.1 ## Redis服务器连接端口 spring.redis.port=6379 ## Redis服务器连接密码(默认为空) spring.redis.password= ## 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 ## 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 ## 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 ## 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 ## 连接超时时间(毫秒) spring.redis.timeout=0 |
1
2
|
Serializable java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
package org.spring.springboot.domain; import java.io.Serializable; /** * 城市实体类 * * Created by bysocket on 07 /02/2017 . */ public class City implements Serializable { private static final long serialVersionUID = -1L; /** * 城市编号 */ private Long id ; /** * 省份编号 */ private Long provinceId; /** * 城市名称 */ private String cityName; /** * 描述 */ private String description; public Long getId() { return id ; } public void setId(Long id ) { this. id = id ; } public Long getProvinceId() { return provinceId; } public void setProvinceId(Long provinceId) { this.provinceId = provinceId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "City{" + "id=" + id + ", provinceId=" + provinceId + ", cityName='" + cityName + '\ '' + ", description='" + description + '\ '' + '}' ; } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
package org.spring.springboot.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.springboot.dao.CityDao; import org.spring.springboot.domain.City; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import java.util.List; import java.util.concurrent.TimeUnit; /** * 城市业务逻辑实现类 * <p> * Created by bysocket on 07 /02/2017 . */ @Service public class CityServiceImpl implements CityService { private static final Logger LOGGER = LoggerFactory.getLogger(CityServiceImpl.class); @Autowired private CityDao cityDao; @Autowired private RedisTemplate redisTemplate; /** * 获取城市逻辑: * 如果缓存存在,从缓存中获取城市信息 * 如果缓存不存在,从 DB 中获取城市信息,然后插入缓存 */ public City findCityById(Long id ) { // 从缓存中获取城市信息 String key = "city_" + id ; ValueOperations<String, City> operations = redisTemplate.opsForValue(); // 缓存存在 boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { City city = operations.get(key); LOGGER.info( "CityServiceImpl.findCityById() : 从缓存中获取了城市 >> " + city.toString()); return city; } // 从 DB 中获取城市信息 City city = cityDao.findById( id ); // 插入缓存 operations. set (key, city, 10, TimeUnit.SECONDS); LOGGER.info( "CityServiceImpl.findCityById() : 城市插入缓存 >> " + city.toString()); return city; } @Override public Long saveCity(City city) { return cityDao.saveCity(city); } /** * 更新城市逻辑: * 如果缓存存在,删除 * 如果缓存不存在,不操作 */ @Override public Long updateCity(City city) { Long ret = cityDao.updateCity(city); // 缓存存在,删除缓存 String key = "city_" + city.getId(); boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); LOGGER.info( "CityServiceImpl.updateCity() : 从缓存中删除城市 >> " + city.toString()); } return ret; } @Override public Long deleteCity(Long id ) { Long ret = cityDao.deleteCity( id ); // 缓存存在,删除缓存 String key = "city_" + id ; boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { redisTemplate.delete(key); LOGGER.info( "CityServiceImpl.deleteCity() : 从缓存中删除城市 ID >> " + id ); } return ret; } } |
五、小结
Spring Boot 整合 Redis 实现缓存操作的更多相关文章
- Spring Boot 整合Redis 实现缓存
本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解 ...
- SpringBoot入门系列(七)Spring Boot整合Redis缓存
前面介绍了Spring Boot 中的整合Mybatis并实现增删改查,.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/ ...
- Spring Boot + Mybatis + Redis二级缓存开发指南
Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...
- (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】
[本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...
- Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能
Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能 开篇 现在的网站基本都有邮件注册功能,毕竟可以通过邮件定期的给用户发送一些 垃圾邮件 精选推荐
- Spring Boot 集成 Redis 实现缓存机制
本文章牵涉到的技术点比较多:spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对以上这些技术点有一定的了解或者也可以先看看这篇文章 ...
- (转)spring boot整合redis
一篇写的更清晰的文章,包括redis序列化:http://makaidong.com/ncjava/330749_5285125.html 1.项目目录结构 2.引入所需jar包 <!-- Sp ...
- spring boot 2.x 系列 —— spring boot 整合 redis
文章目录 一.说明 1.1 项目结构 1.2 项目主要依赖 二.整合 Redis 2.1 在application.yml 中配置redis数据源 2.2 封装redis基本操作 2.3 redisT ...
- Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis
在 Redis 出现之前,我们的缓存框架各种各样,有了 Redis ,缓存方案基本上都统一了,关于 Redis,松哥之前有一个系列教程,尚不了解 Redis 的小伙伴可以参考这个教程: Redis 教 ...
随机推荐
- AR入门系列-02-Vuforia在Unity3d编辑器的使用
到unity3d的官网下载 地址:https://store.unity.com/?_ga=1.1496562.231401799.1487590551 个人版功能齐全免费,个人开发者基本够用,本案例 ...
- VUE2.0实现购物车和地址选配功能学习第三节
第三节 使用v-for渲染商品列表 1.使用vue-resource插件引入json数据 (注:在谷歌中调试打断点-- ,console还可以输出vm,res等属性列表,或者productList等一 ...
- Selenium 切换句柄
最近用了网络上别人的一段切换窗口的code每次成功了,不错,学习 // 根据Title切换新窗口 public boolean switchToWindow_Title(WebDriver drive ...
- node c++多线程插件构想
最近想写一个node的c++插件实现线程.提供的api使用回调并进行二次包装使其返回一个promise,并且要求需要在工作线程里执行的函数为async函数.如果是node7.0以下的版本,函数必须返回 ...
- 关于 jquery html 动态添加的元素绑定事件——On()
Ajax动态生成的数据,动作绑定需要重新执行 $(document).on('click','.btn1',function(){}); 替换: $('btn1').on('click') = fun ...
- 2017-3-17 SQL server 数据库 视图,事务,备份还原,分离附加
1.视图:只能查看,不能增删改不能有重复列 create view 名字as查询语句 2.事务:保证流程的完整执行 begin tran --开始事务监控 被监控的代码 ... ...if @@ERR ...
- 10分钟精通SharePoint - SharePoint升级
类型: b2b(安装更新)和v2v(跨版本升级) 内容:二进制文件和数据库 过程: 升级前检查 - 检查场内数据,配置和自定义等等 升级准备和计划 - 根据需要和升级检查制定相应计划和准备工作 ...
- 字符集&各种编码&编码解码
要理解乱码问题,首先需要理解几个概念:字符集.编码.编码规则.乱码 1. 字符集: 字符(Character)是各种文字和符号的总称,包括各国家文字.标点符号.图形符号.数字等.字符集(Charact ...
- php线程安全与非线程安全版的区别
Thread Safe(线程安全)和 None Thread Safe(非线程安全) 背景: Linux/Unix系统采用多进程的工作方式,而Windows系统采用多线程的工作方式. CGI模式是建立 ...
- 一场完美的“秒杀”:API加速的业务逻辑
清晨,我被一个客户电话惊醒,客户异常焦急,寻问CDN能不能帮助他们解决“秒杀”的问题,他们昨天刚刚进行了“整点秒杀活动”,结果并发量过大,导致服务宕机,用户投诉. 为了理清思路,我问了对方三个问题: ...