一、緩存的應用場景
二、更新緩存的政策
三、運作 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