一、缓存的应用场景
二、更新缓存的策略
三、运行 springboot-mybatis-redis 工程案例
四、springboot-mybatis-redis 工程代码配置详解
运行环境:
mac os 10.12.x
jdk 8 +
redis 3.2.8
spring boot 1.5.1.release
什么是缓存?
在互联网场景下,尤其2c端大流量场景下,需要将一些经常展现和不会频繁变更的数据,存放在存取速率更快的地方。缓存就是一个存储器,在技术选型中,常用 redis 作为缓存数据库。缓存主要是在获取资源方便性能优化的关键方面。
redis 是一个高性能的 key-value 数据库。github 地址:https://github.com/antirez/redis 。github 是这么描述的:
redis is an in-memory database that persists on disk. the data model
is key-value, but many different kind of values are supported: strings,
lists, sets, sorted sets, hashes, hyperloglogs, bitmaps.
缓存的应用场景有哪些呢?
比如常见的电商场景,根据商品 id 获取商品信息时,店铺信息和商品详情信息就可以缓存在 redis,直接从 redis 获取。减少了去数据库查询的次数。但会出现新的问题,就是如何对缓存进行更新?这就是下面要讲的。
缓存更新的模式有四种:cache aside, read through, write through, write behind caching。
这里我们使用的是 cache aside 策略,从三个维度:(摘自 耗子叔叔博客)
失效:应用程序先从cache取数据,没有得到,则从数据库中取数据,成功后,放到缓存中。
命中:应用程序从cache中取数据,取到后返回。
更新:先把数据存到数据库中,成功后,再让缓存失效。
大致流程如下:
获取商品详情举例
a. 从商品 cache 中获取商品详情,如果存在,则返回获取 cache 数据返回。
b. 如果不存在,则从商品 db 中获取。获取成功后,将数据存到 cache 中。则下次获取商品详情,就可以从 cache 就可以得到商品详情数据。
c. 从商品 db 中更新或者删除商品详情成功后,则从缓存中删除对应商品的详情缓存
下面开始运行工程步骤(quick start):
1.数据库和 redis 准备
a.创建数据库 springbootdb:
create database springbootdb
b.创建表 city :(因为我喜欢徒步)
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;
c.插入数据
insert city values (1 ,1,'温岭市','bysocket 的家在温岭。');
d.本地安装 redis
详见写过的文章《 redis 安装 》http://www.bysocket.com/?p=917
2. springboot-mybatis-redis 工程项目结构介绍
springboot-mybatis-redis 工程项目结构如下图所示:
org.spring.springboot.controller - controller 层
org.spring.springboot.dao - 数据操作层 dao
org.spring.springboot.domain - 实体类
org.spring.springboot.service - 业务逻辑层
application - 应用启动类
application.properties - 应用配置文件,应用启动会自动读取配置
3.改数据库配置
打开 application.properties 文件, 修改相应的数据源配置,比如数据源地址、账号、密码等。
(如果不是用 mysql,自行添加连接驱动 pom,然后修改驱动名配置。)
4.编译工程
在项目根目录 springboot-learning-example,运行 maven 指令:
mvn clean install
5.运行工程
右键运行 springboot-mybatis-redis 工程 application 应用启动类的 main 函数。
项目运行成功后,这是个 http over json 服务项目。所以用 postman 工具可以如下操作
根据 id,获取城市信息
get http://127.0.0.1:8080/api/city/1
再请求一次,获取城市信息会发现数据获取的耗时快了很多。服务端 console 输出的日志:
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='水好,天蓝'}
可见,第一次是从数据库 db 获取数据,并插入缓存,第二次直接从缓存中取。
更新城市信息
put http://127.0.0.1:8080/api/city
删除城市信息
delete http://127.0.0.1:8080/api/city/2
这两种操作中,如果缓存有对应的数据,则删除缓存。服务端 console 输出的日志:
12017-04-13 18:29:52.248 info 13038 --- [nio-8080-exec-9] o.s.s.service.impl.cityserviceimpl : cityserviceimpl.deletecity() : 从缓存中删除城市 id >> 12
这里,我强烈推荐 注解 的方式实现对象的缓存。但是这里为了更好说明缓存更新策略。下面讲讲工程代码的实现。
pom.xml 依赖配置:
<?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 依赖 -->
<artifactid>spring-boot-starter-web</artifactid>
<!-- spring boot test 依赖 -->
<artifactid>spring-boot-starter-test</artifactid>
<scope>test</scope>
<!-- spring boot mybatis 依赖 -->
<groupid>org.mybatis.spring.boot</groupid>
<artifactid>mybatis-spring-boot-starter</artifactid>
<version>${mybatis-spring-boot}</version>
<!-- mysql 连接驱动依赖 -->
<groupid>mysql</groupid>
<artifactid>mysql-connector-java</artifactid>
<version>${mysql-connector}</version>
<!-- junit -->
<groupid>junit</groupid>
<artifactid>junit</artifactid>
<version>4.12</version>
</dependencies>
</project>
包括了 spring boot reids 依赖、 mysql 依赖和 mybatis 依赖。
在 application.properties 应用配置文件,增加 redis 相关配置
## 数据源配置
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
详细解释可以参考注释。对应的配置类:org.springframework.boot.autoconfigure.data.redis.redisproperties
cityrestcontroller 控制层依旧是 restful 风格的,详情可以参考《springboot 实现 restful
服务,基于 http / json 传输》。 http://www.bysocket.com/?p=1627 domain 对象 city
必须实现序列化,因为需要将对象序列化后存储到 redis。如果没实现 serializable ,控制台会爆出以下异常:
serializable
java.lang.illegalargumentexception: defaultserializer requires a serializable payload but received an object of type
city.java 城市对象:
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 + '\'' +
'}';
}
如果需要自定义序列化实现,只要实现 redisserializer 接口去实现即可,然后在使用 redistemplate.setvalueserializer 方法去设置你实现的序列化实现。
主要还是城市业务逻辑实现类 cityserviceimpl.java:
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>
@service
public class cityserviceimpl implements cityservice {
private static final logger logger = loggerfactory.getlogger(cityserviceimpl.class);
@autowired
private citydao citydao;
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;
public long savecity(city city) {
return citydao.savecity(city);
* 更新城市逻辑:
* 如果缓存存在,删除
* 如果缓存不存在,不操作
public long updatecity(city city) {
long ret = citydao.updatecity(city);
// 缓存存在,删除缓存
string key = "city_" + city.getid();
redistemplate.delete(key);
logger.info("cityserviceimpl.updatecity() : 从缓存中删除城市 >> " + city.tostring());
return ret;
public long deletecity(long id) {
long ret = citydao.deletecity(id);
logger.info("cityserviceimpl.deletecity() : 从缓存中删除城市 id >> " + id);
首先这里注入了 redistemplate 对象。联想到 spring 的 jdbctemplate ,redistemplate 封装了
redisconnection,具有连接管理,序列化和 redis 操作等功能。还有针对 string 的支持对象
stringredistemplate。
redis 操作视图接口类用的是 valueoperations,对应的是 redis string/value
操作。还有其他的操作视图,listoperations、setoperations、zsetoperations 和
hashoperations 。valueoperations 插入缓存是可以设置失效时间,这里设置的失效时间是 10 s。
回到更新缓存的逻辑
a. findcitybyid 获取城市逻辑:
如果缓存存在,从缓存中获取城市信息
如果缓存不存在,从 db 中获取城市信息,然后插入缓存
b. deletecity 删除 / updatecity 更新城市逻辑:
如果缓存存在,删除
如果缓存不存在,不操作
其他不明白的,可以 git clone 下载工程 springboot-learning-example ,工程代码注解很详细。 https://github.com/jeffli1993/springboot-learning-example。
五、小结
本文涉及到 spring boot 在使用 redis 缓存时,一个是缓存对象需要序列化,二个是缓存更新策略是如何的。
作者:泥沙砖瓦浆木匠
来源:51cto