自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Spring Boot 整合 Redis 實現(xiàn)緩存操作

開發(fā) 后端 Redis
在互聯(lián)網(wǎng)場景下,尤其2C端大流量場景下,需要將一些經(jīng)常展現(xiàn)和不會頻繁變更的數(shù)據(jù),存放在存取速率更快的地方。緩存就是一個存儲器,在技術(shù)選型中,常用Redis作為緩存數(shù)據(jù)庫。緩存主要是在獲取資源方便性能優(yōu)化的關(guān)鍵方面。

[[188693]]

一、緩存的應(yīng)用場景

二、更新緩存的策略

三、運行 springboot-mybatis-redis 工程案例

四、springboot-mybatis-redis 工程代碼配置詳解

運行環(huán)境:

Mac OS 10.12.x

JDK 8 +

Redis 3.2.8

Spring Boot 1.5.1.RELEASE

一、緩存的應(yīng)用場景

什么是緩存?

在互聯(lián)網(wǎng)場景下,尤其2C端大流量場景下,需要將一些經(jīng)常展現(xiàn)和不會頻繁變更的數(shù)據(jù),存放在存取速率更快的地方。緩存就是一個存儲器,在技術(shù)選型中,常用 Redis 作為緩存數(shù)據(jù)庫。緩存主要是在獲取資源方便性能優(yōu)化的關(guān)鍵方面。

Redis 是一個高性能的 key-value 數(shù)據(jù)庫。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.

緩存的應(yīng)用場景有哪些呢?

比如常見的電商場景,根據(jù)商品 ID 獲取商品信息時,店鋪信息和商品詳情信息就可以緩存在 Redis,直接從 Redis 獲取。減少了去數(shù)據(jù)庫查詢的次數(shù)。但會出現(xiàn)新的問題,就是如何對緩存進行更新?這就是下面要講的。

二、更新緩存的策略

緩存更新的模式有四種:Cache aside, Read through, Write through, Write behind caching。

這里我們使用的是 Cache Aside 策略,從三個維度:(摘自 耗子叔叔博客)

失效:應(yīng)用程序先從cache取數(shù)據(jù),沒有得到,則從數(shù)據(jù)庫中取數(shù)據(jù),成功后,放到緩存中。

***:應(yīng)用程序從cache中取數(shù)據(jù),取到后返回。

更新:先把數(shù)據(jù)存到數(shù)據(jù)庫中,成功后,再讓緩存失效。

大致流程如下:

獲取商品詳情舉例

a. 從商品 Cache 中獲取商品詳情,如果存在,則返回獲取 Cache 數(shù)據(jù)返回。

b. 如果不存在,則從商品 DB 中獲取。獲取成功后,將數(shù)據(jù)存到 Cache 中。則下次獲取商品詳情,就可以從 Cache 就可以得到商品詳情數(shù)據(jù)。

c. 從商品 DB 中更新或者刪除商品詳情成功后,則從緩存中刪除對應(yīng)商品的詳情緩存

三、運行 springboot-mybatis-redis 工程案例

git clone 下載工程 springboot-learning-example ,項目地址見 GitHub – https://github.com/JeffLi1993/springboot-learning-example。

下面開始運行工程步驟(Quick Start):

1.數(shù)據(jù)庫和 Redis 準(zhǔn)備

a.創(chuàng)建數(shù)據(jù)庫 springbootdb:

  1. CREATE DATABASE springbootdb 

b.創(chuàng)建表 city :(因為我喜歡徒步)

  1. DROP TABLE IF EXISTS  `city`; 
  2. CREATE TABLE `city` ( 
  3.   `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '城市編號'
  4.   `province_id` int(10) unsigned  NOT NULL COMMENT '省份編號'
  5.   `city_name` varchar(25) DEFAULT NULL COMMENT '城市名稱'
  6.   `description` varchar(25) DEFAULT NULL COMMENT '描述'
  7.   PRIMARY KEY (`id`) 
  8. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 

c.插入數(shù)據(jù)

  1. INSERT city VALUES (1 ,1,'溫嶺市','BYSocket 的家在溫嶺。'); 

d.本地安裝 Redis

詳見寫過的文章《 Redis 安裝 》http://www.bysocket.com/?p=917

2. springboot-mybatis-redis 工程項目結(jié)構(gòu)介紹

  1. springboot-mybatis-redis 工程項目結(jié)構(gòu)如下圖所示: 
  2. org.spring.springboot.controller - Controller 層 
  3. org.spring.springboot.dao - 數(shù)據(jù)操作層 DAO 
  4. org.spring.springboot.domain - 實體類 
  5. org.spring.springboot.service - 業(yè)務(wù)邏輯層 
  6. Application - 應(yīng)用啟動類 
  7. application.properties - 應(yīng)用配置文件,應(yīng)用啟動會自動讀取配置 

3.改數(shù)據(jù)庫配置

打開 application.properties 文件, 修改相應(yīng)的數(shù)據(jù)源配置,比如數(shù)據(jù)源地址、賬號、密碼等。

(如果不是用 MySQL,自行添加連接驅(qū)動 pom,然后修改驅(qū)動名配置。)

4.編譯工程

在項目根目錄 springboot-learning-example,運行 maven 指令:

  1. mvn clean install 

5.運行工程

右鍵運行 springboot-mybatis-redis 工程 Application 應(yīng)用啟動類的 main 函數(shù)。

項目運行成功后,這是個 HTTP OVER JSON 服務(wù)項目。所以用 postman 工具可以如下操作

根據(jù) ID,獲取城市信息

GET http://127.0.0.1:8080/api/city/1

再請求一次,獲取城市信息會發(fā)現(xiàn)數(shù)據(jù)獲取的耗時快了很多。服務(wù)端 Console 輸出的日志:

  1. 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='水好,天藍'} 
  2. 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='水好,天藍'} 

可見,***次是從數(shù)據(jù)庫 DB 獲取數(shù)據(jù),并插入緩存,第二次直接從緩存中取。

更新城市信息

PUT http://127.0.0.1:8080/api/city

刪除城市信息

DELETE http://127.0.0.1:8080/api/city/2

這兩種操作中,如果緩存有對應(yīng)的數(shù)據(jù),則刪除緩存。服務(wù)端 Console 輸出的日志:

  1. 12017-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 工程代碼配置詳解

這里,我強烈推薦 注解 的方式實現(xiàn)對象的緩存。但是這里為了更好說明緩存更新策略。下面講講工程代碼的實現(xiàn)。

pom.xml 依賴配置:

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
  4.     <modelVersion>4.0.0</modelVersion> 
  5.   
  6.     <groupId>springboot</groupId> 
  7.     <artifactId>springboot-mybatis-redis</artifactId> 
  8.     <version>0.0.1-SNAPSHOT</version> 
  9.     <name>springboot-mybatis-redis :: 整合 Mybatis 并使用 Redis 作為緩存</name
  10.   
  11.     <!-- Spring Boot 啟動父依賴 --> 
  12.     <parent> 
  13.         <groupId>org.springframework.boot</groupId> 
  14.         <artifactId>spring-boot-starter-parent</artifactId> 
  15.         <version>1.5.1.RELEASE</version> 
  16.     </parent> 
  17.   
  18.     <properties> 
  19.         <mybatis-spring-boot>1.2.0</mybatis-spring-boot> 
  20.         <mysql-connector>5.1.39</mysql-connector> 
  21.         <spring-boot-starter-redis-version>1.3.2.RELEASE</spring-boot-starter-redis-version> 
  22.     </properties> 
  23.   
  24.     <dependencies> 
  25.   
  26.         <!-- Spring Boot Reids 依賴 --> 
  27.         <dependency> 
  28.             <groupId>org.springframework.boot</groupId> 
  29.             <artifactId>spring-boot-starter-redis</artifactId> 
  30.             <version>${spring-boot-starter-redis-version}</version> 
  31.         </dependency> 
  32.   
  33.         <!-- Spring Boot Web 依賴 --> 
  34.         <dependency> 
  35.             <groupId>org.springframework.boot</groupId> 
  36.             <artifactId>spring-boot-starter-web</artifactId> 
  37.         </dependency> 
  38.   
  39.         <!-- Spring Boot Test 依賴 --> 
  40.         <dependency> 
  41.             <groupId>org.springframework.boot</groupId> 
  42.             <artifactId>spring-boot-starter-test</artifactId> 
  43.             <scope>test</scope> 
  44.         </dependency> 
  45.   
  46.         <!-- Spring Boot Mybatis 依賴 --> 
  47.         <dependency> 
  48.             <groupId>org.mybatis.spring.boot</groupId> 
  49.             <artifactId>mybatis-spring-boot-starter</artifactId> 
  50.             <version>${mybatis-spring-boot}</version> 
  51.         </dependency> 
  52.   
  53.         <!-- MySQL 連接驅(qū)動依賴 --> 
  54.         <dependency> 
  55.             <groupId>mysql</groupId> 
  56.             <artifactId>mysql-connector-java</artifactId> 
  57.             <version>${mysql-connector}</version> 
  58.         </dependency> 
  59.   
  60.         <!-- Junit --> 
  61.         <dependency> 
  62.             <groupId>junit</groupId> 
  63.             <artifactId>junit</artifactId> 
  64.             <version>4.12</version> 
  65.         </dependency> 
  66.     </dependencies> 
  67. </project> 

包括了 Spring Boot Reids 依賴、 MySQL 依賴和 Mybatis 依賴。

在 application.properties 應(yīng)用配置文件,增加 Redis 相關(guān)配置

  1. ## 數(shù)據(jù)源配置 
  2. spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8 
  3. spring.datasource.username=root 
  4. spring.datasource.password=123456 
  5. spring.datasource.driver-class-name=com.mysql.jdbc.Driver 
  6.   
  7. ## Mybatis 配置 
  8. mybatis.typeAliasesPackage=org.spring.springboot.domain 
  9. mybatis.mapperLocations=classpath:mapper/*.xml 
  10.   
  11. ## Redis 配置 
  12. ## Redis數(shù)據(jù)庫索引(默認為0) 
  13. spring.redis.database=0 
  14. ## Redis服務(wù)器地址 
  15. spring.redis.host=127.0.0.1 
  16. ## Redis服務(wù)器連接端口 
  17. spring.redis.port=6379 
  18. ## Redis服務(wù)器連接密碼(默認為空) 
  19. spring.redis.password
  20. ## 連接池***連接數(shù)(使用負值表示沒有限制) 
  21. spring.redis.pool.max-active=8 
  22. ## 連接池***阻塞等待時間(使用負值表示沒有限制) 
  23. spring.redis.pool.max-wait=-1 
  24. ## 連接池中的***空閑連接 
  25. spring.redis.pool.max-idle=8 
  26. ## 連接池中的最小空閑連接 
  27. spring.redis.pool.min-idle=0 
  28. ## 連接超時時間(毫秒) 
  29. spring.redis.timeout=0 

詳細解釋可以參考注釋。對應(yīng)的配置類:org.springframework.boot.autoconfigure.data.redis.RedisProperties

CityRestController 控制層依舊是 Restful 風(fēng)格的,詳情可以參考《Springboot 實現(xiàn) Restful 服務(wù),基于 HTTP / JSON 傳輸》。 http://www.bysocket.com/?p=1627 domain 對象 City 必須實現(xiàn)序列化,因為需要將對象序列化后存儲到 Redis。如果沒實現(xiàn) Serializable ,控制臺會爆出以下異常:

  1. Serializable 
  2. java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type 

City.java 城市對象:

  1. package org.spring.springboot.domain; 
  2.   
  3. import java.io.Serializable
  4.   
  5. /** 
  6.  * 城市實體類 
  7.  * 
  8.  * Created by bysocket on 07/02/2017. 
  9.  */ 
  10. public class City implements Serializable { 
  11.   
  12.     private static final long serialVersionUID = -1L; 
  13.   
  14.     /** 
  15.      * 城市編號 
  16.      */ 
  17.     private Long id; 
  18.   
  19.     /** 
  20.      * 省份編號 
  21.      */ 
  22.     private Long provinceId; 
  23.   
  24.     /** 
  25.      * 城市名稱 
  26.      */ 
  27.     private String cityName; 
  28.   
  29.     /** 
  30.      * 描述 
  31.      */ 
  32.     private String description; 
  33.   
  34.     public Long getId() { 
  35.         return id; 
  36.     } 
  37.   
  38.     public void setId(Long id) { 
  39.         this.id = id; 
  40.     } 
  41.   
  42.     public Long getProvinceId() { 
  43.         return provinceId; 
  44.     } 
  45.   
  46.     public void setProvinceId(Long provinceId) { 
  47.         this.provinceId = provinceId; 
  48.     } 
  49.   
  50.     public String getCityName() { 
  51.         return cityName; 
  52.     } 
  53.   
  54.     public void setCityName(String cityName) { 
  55.         this.cityName = cityName; 
  56.     } 
  57.   
  58.     public String getDescription() { 
  59.         return description; 
  60.     } 
  61.   
  62.     public void setDescription(String description) { 
  63.         this.description = description; 
  64.     } 
  65.   
  66.     @Override 
  67.     public String toString() { 
  68.         return "City{" + 
  69.                 "id=" + id + 
  70.                 ", provinceId=" + provinceId + 
  71.                 ", cityName='" + cityName + '\'' + 
  72.                 ", description='" + description + '\'' + 
  73.                 '}'
  74.     } 

如果需要自定義序列化實現(xiàn),只要實現(xiàn) RedisSerializer 接口去實現(xiàn)即可,然后在使用 RedisTemplate.setValueSerializer 方法去設(shè)置你實現(xiàn)的序列化實現(xiàn)。

主要還是城市業(yè)務(wù)邏輯實現(xiàn)類 CityServiceImpl.java:

  1. package org.spring.springboot.service.impl; 
  2.   
  3. import org.slf4j.Logger; 
  4. import org.slf4j.LoggerFactory; 
  5. import org.spring.springboot.dao.CityDao; 
  6. import org.spring.springboot.domain.City; 
  7. import org.spring.springboot.service.CityService; 
  8. import org.springframework.beans.factory.annotation.Autowired; 
  9. import org.springframework.data.redis.core.RedisTemplate; 
  10. import org.springframework.data.redis.core.StringRedisTemplate; 
  11. import org.springframework.data.redis.core.ValueOperations; 
  12. import org.springframework.stereotype.Service; 
  13.   
  14. import java.util.List; 
  15. import java.util.concurrent.TimeUnit; 
  16.   
  17. /** 
  18.  * 城市業(yè)務(wù)邏輯實現(xiàn)類 
  19.  * <p> 
  20.  * Created by bysocket on 07/02/2017. 
  21.  */ 
  22. @Service 
  23. public class CityServiceImpl implements CityService { 
  24.   
  25.     private static final Logger LOGGER = LoggerFactory.getLogger(CityServiceImpl.class); 
  26.   
  27.     @Autowired 
  28.     private CityDao cityDao; 
  29.   
  30.     @Autowired 
  31.     private RedisTemplate redisTemplate; 
  32.   
  33.     /** 
  34.      * 獲取城市邏輯: 
  35.      * 如果緩存存在,從緩存中獲取城市信息 
  36.      * 如果緩存不存在,從 DB 中獲取城市信息,然后插入緩存 
  37.      */ 
  38.     public City findCityById(Long id) { 
  39.         // 從緩存中獲取城市信息 
  40.         String key = "city_" + id; 
  41.         ValueOperations<String, City> operations = redisTemplate.opsForValue(); 
  42.   
  43.         // 緩存存在 
  44.         boolean hasKey = redisTemplate.hasKey(key); 
  45.         if (hasKey) { 
  46.             City city = operations.get(key); 
  47.   
  48.             LOGGER.info("CityServiceImpl.findCityById() : 從緩存中獲取了城市 >> " + city.toString()); 
  49.             return city; 
  50.         } 
  51.   
  52.         // 從 DB 中獲取城市信息 
  53.         City city = cityDao.findById(id); 
  54.   
  55.         // 插入緩存 
  56.         operations.set(key, city, 10, TimeUnit.SECONDS); 
  57.         LOGGER.info("CityServiceImpl.findCityById() : 城市插入緩存 >> " + city.toString()); 
  58.   
  59.         return city; 
  60.     } 
  61.   
  62.     @Override 
  63.     public Long saveCity(City city) { 
  64.         return cityDao.saveCity(city); 
  65.     } 
  66.   
  67.     /** 
  68.      * 更新城市邏輯: 
  69.      * 如果緩存存在,刪除 
  70.      * 如果緩存不存在,不操作 
  71.      */ 
  72.     @Override 
  73.     public Long updateCity(City city) { 
  74.         Long ret = cityDao.updateCity(city); 
  75.   
  76.         // 緩存存在,刪除緩存 
  77.         String key = "city_" + city.getId(); 
  78.         boolean hasKey = redisTemplate.hasKey(key); 
  79.         if (hasKey) { 
  80.             redisTemplate.delete(key); 
  81.   
  82.             LOGGER.info("CityServiceImpl.updateCity() : 從緩存中刪除城市 >> " + city.toString()); 
  83.         } 
  84.   
  85.         return ret; 
  86.     } 
  87.   
  88.     @Override 
  89.     public Long deleteCity(Long id) { 
  90.   
  91.         Long ret = cityDao.deleteCity(id); 
  92.   
  93.         // 緩存存在,刪除緩存 
  94.         String key = "city_" + id; 
  95.         boolean hasKey = redisTemplate.hasKey(key); 
  96.         if (hasKey) { 
  97.             redisTemplate.delete(key); 
  98.   
  99.             LOGGER.info("CityServiceImpl.deleteCity() : 從緩存中刪除城市 ID >> " + id); 
  100.         } 
  101.         return ret; 
  102.     } 
  103.   

首先這里注入了 RedisTemplate 對象。聯(lián)想到 Spring 的 JdbcTemplate ,RedisTemplate 封裝了 RedisConnection,具有連接管理,序列化和 Redis 操作等功能。還有針對 String 的支持對象 StringRedisTemplate。

Redis 操作視圖接口類用的是 ValueOperations,對應(yīng)的是 Redis String/Value 操作。還有其他的操作視圖,ListOperations、SetOperations、ZSetOperations 和 HashOperations 。ValueOperations 插入緩存是可以設(shè)置失效時間,這里設(shè)置的失效時間是 10 s。

回到更新緩存的邏輯

a. findCityById 獲取城市邏輯:

如果緩存存在,從緩存中獲取城市信息

如果緩存不存在,從 DB 中獲取城市信息,然后插入緩存

b. deleteCity 刪除 / updateCity 更新城市邏輯:

如果緩存存在,刪除

如果緩存不存在,不操作

其他不明白的,可以 git clone 下載工程 springboot-learning-example ,工程代碼注解很詳細。 https://github.com/JeffLi1993/springboot-learning-example。

五、小結(jié)

本文涉及到 Spring Boot 在使用 Redis 緩存時,一個是緩存對象需要序列化,二個是緩存更新策略是如何的。

摘要: 原創(chuàng)出處 www.bysocket.com 「泥瓦匠BYSocket 」歡迎轉(zhuǎn)載,保留摘要,謝謝!

 

責(zé)任編輯:武曉燕 來源: oschina博客
相關(guān)推薦

2020-08-19 08:55:47

Redis緩存數(shù)據(jù)庫

2015-12-28 10:48:44

RedisSpring緩存實例

2018-11-02 15:45:41

Spring BootRedis數(shù)據(jù)庫

2025-03-26 03:25:00

SpringGuavaCaffeine

2019-03-28 11:07:56

Spring BootRedis緩存

2024-10-15 16:01:19

SpringBoot緩存預(yù)熱

2024-11-11 10:02:37

Spring搜索數(shù)據(jù)

2020-01-10 15:42:13

SpringBootRedis數(shù)據(jù)庫

2023-10-12 08:00:48

2022-12-23 08:28:42

策略模式算法

2017-05-19 14:47:24

Spring Boot Elasticsea場景

2017-10-17 15:14:33

Spring BooThymeleafWeb

2022-07-21 11:04:53

Swagger3Spring

2020-08-19 17:56:46

緩存Redis集中式

2020-06-29 07:43:12

緩存RedisSpringBoot

2020-07-15 16:50:57

Spring BootRedisJava

2022-08-24 08:42:59

Minio存儲Golang

2025-02-21 12:00:00

SpringBoot防重復(fù)提交緩存機制

2023-10-12 10:32:51

2024-01-10 14:45:46

Redis數(shù)據(jù)庫存儲
點贊
收藏

51CTO技術(shù)棧公眾號