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;
}
}
|
五、小结
转载于:https://www.cnblogs.com/Soy-technology/p/11025089.html
Spring Boot 整合Redis 实现缓存相关推荐
- Spring Boot 整合 Redis 实现缓存操作
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』 本文提纲 一.缓 ...
- Spring Boot整合Redis实现缓存
前言 在此章,我们将 SpringBoot 集成 Redis缓存,Redis是一个开源的,基于内存的数据结构存储,可以用作数据库.缓存和消息代理,在本章仅讲解缓存集成.一键获取源码地址 准备工作 当前 ...
- Spring boot - 整合 Redis缓存(上)
一.配置Pom文件 在使用spring boot 2.0整合redis时遇到了好多问题,网上很多例子都是1.x版本的.故2.0没有折腾好所以将2.0降到了1.5.降级后由于thymeleaf版本也会从 ...
- 猿创征文 | 微服务 Spring Boot 整合Redis 实战开发解决高并发数据缓存
文章目录 一.什么是 缓存? ⛅为什么用缓存? ⚡如何使用缓存 二.实现一个商家缓存 ⌛环境搭建 ♨️核心源码 ✅测试接口 三.采用 微服务 Spring Boot 注解开启缓存 ✂️@CacheEn ...
- 十一、Spring Boot整合Redis(一)
Spring Boot整合Redis 1. SpringBoot+单例Redis 1)引入依赖 <dependency> <groupId>org.springf ...
- Spring boot整合Redis(入门教程)
目录 源码分析 jedis VS lettuce 整合测试 导入依赖 配置连接 测试 存入字符串 存入对象 五大数据类型操作 自定义RedisConfig 存入对象 Redis工具类(常用API) 以 ...
- 大聪明教你学Java | Spring Boot 整合 Redis 实现访问量统计
前言 之前开发系统的时候客户提到了一个需求:需要统计某些页面的访问量,记得当时还纠结了一阵子,不知道怎么去实现这个功能,后来还是在大佬的带领下借助 Redis 实现了这个功能.今天又回想起了这件事,正 ...
- Spring Boot整合Redis以及Redis的原理
Redis的原理及知识 Redis简介 redis是一个key-value.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合). ...
- Spring Boot基础学习笔记08:Spring Boot整合Redis
文章目录 零.学习目标 1.熟悉Redis相关概念 2.掌握使用Spring Boot整合Redis 一.Redis概述 1.Redis简介 2.Redis优点 (1)存取速度快 (2)数据类型丰富 ...
最新文章
- ubuntu16.04 安装微信和qq
- 数据结构(数据库)设计规范
- kali系统网络设置
- [Python人工智能] 二.TensorFlow基础及一元直线预测案例
- 【算法】prim算法(最小生成树)(与Dijkstra算法的比较)
- 定位低效率执行SQL
- C语言 main 函数到底为啥这么写?
- Linux课程笔记 Crond介绍
- java最广泛的运行环境_Java运行环境下载|Java SE Runtime Environment(Java运行环境)8.0.131 官方多语言正式版_ - 极光下载站...
- 针对金融级交易场景的严苛技术要求,如何修炼这门“必修课”?
- 郑州没有互联网 | 畅言
- Vue路由及路由守卫
- 【Buzz】简介及第一个案例
- SAP PI SLD RZ70 系统架构目录数据提供者 HTTP(S) 配置
- Maven Helper插件下载
- java put 语句_Java put语句
- java中的LinkedList(链表)与ArrayList(动态数组):(2)尝试简单实现LinkedList
- NTC热敏电阻检测温度
- Spring AOP 切面记录操作日志
- Java job interview:运用所学理论、知识和技能解决实际问题的能力
热门文章
- android用户界面之菜单(Menu)教程实例汇总
- objective-c abort() 与 exit() 函数的区别
- 数据库设计的三大范式
- OpenCV+python:分水岭算法
- 算法及其复杂度度量简介
- 基于深度学习的口罩识别与检测PyTorch实现
- xdoj 1009线段树求约瑟夫环
- java停车管理系统中期检查_java毕业设计_springboot框架的停车场收费管理系统
- 查询oracle模式对象信息,ORACLE 模式和模式对象
- java 根据圆心计算圆弧上点的经纬度_冲压件展开计算方法(二),转发给每一位冲压人...