Spring Boot 整合 Redis 实现缓存操作

在互联网场景下,尤其2C端大流量场景下,需要将一些经常展现和不会频繁变更的数据,存放在存取速率更快的地方。缓存就是一个存储器,在技术选型中,常用Redis作为缓存数据库。缓存主要是在获取资源方便性能优化的关键方面。 2017-04-17 10:35:40 Spring BooRedis 操作 Redis缓存技术学习系列之事务处理 我们可以注意到,Redis是一个C/S架构的数据库,在我们目前的认知中,它是通过终端中的一条条命令来存储和读取的,即它是一个非常典型的“请求-响应”模型。可是我们知道在实际的应用中,我们要面对的或许是更为复杂的业务逻辑,因为Redis中不存在传统关系型数据库中表的概念,因此在使用Redis的过程中,我们要面对两个实际的问题,即如何更好的维护数据库中的”键“、如何在高效执行命令的同时保证命令执行成功。

在互联网场景下,尤其2C端大流量场景下,需要将一些经常展现和不会频繁变更的数据,存放在存取速率更快的地方。缓存就是一个存储器,在技术选型中,常用Redis作为缓存数据库。缓存主要是在获取资源方便性能优化的关键方面。

[[188693]]

一、缓存的应用场景

二、更新缓存的策略

三、运行 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 中更新或者删除商品详情成功后,则从缓存中删除对应商品的详情缓存

Spring Boot 整合 Redis 实现缓存操作

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

git clone 下载工程 springboot-learning-example ,项目地址见 GitHub – https://github.com/JeffLi1993/springboot-learning-example

下面开始运行工程步骤(Quick Start):

1.数据库和 Redis 准备

a.创建数据库 springbootdb:

  1. CREATEDATABASEspringbootdb

b.创建表 city :(因为我喜欢徒步)

  1. DROPTABLEIFEXISTS`city`;
  2. CREATETABLE`city`(
  3. `id`int(10)unsignedNOTNULLAUTO_INCREMENTCOMMENT'城市编号',
  4. `province_id`int(10)unsignedNOTNULLCOMMENT'省份编号',
  5. `city_name`varchar(25)DEFAULTNULLCOMMENT'城市名称',
  6. `description`varchar(25)DEFAULTNULLCOMMENT'描述',
  7. PRIMARYKEY(`id`)
  8. )ENGINE=InnoDBAUTO_INCREMENT=1DEFAULTCHARSET=utf8;

c.插入数据

  1. INSERTcityVALUES(1,1,'温岭市','BYSocket的家在温岭。');

d.本地安装 Redis

详见写过的文章《 Redis 安装 》http://www.bysocket.com/?p=917

2. springboot-mybatis-redis 工程项目结构介绍

  1. springboot-mybatis-redis工程项目结构如下图所示:
  2. org.spring.springboot.controller-Controller层
  3. org.spring.springboot.dao-数据操作层DAO
  4. org.spring.springboot.domain-实体类
  5. org.spring.springboot.service-业务逻辑层
  6. Application-应用启动类
  7. application.properties-应用配置文件,应用启动会自动读取配置

3.改数据库配置

打开 application.properties 文件, 修改相应的数据源配置,比如数据源地址、账号、密码等。

(如果不是用 MySQL,自行添加连接驱动 pom,然后修改驱动名配置。)

4.编译工程

在项目根目录 springboot-learning-example,运行 maven 指令:

  1. mvncleaninstall

5.运行工程

右键运行 springboot-mybatis-redis 工程 Application 应用启动类的 main 函数。

项目运行成功后,这是个 HTTP OVER JSON 服务项目。所以用 postman 工具可以如下操作

根据 ID,获取城市信息

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

再请求一次,获取城市信息会发现数据获取的耗时快了很多。服务端 Console 输出的日志:

  1. 2017-04-1318:29:00.273INFO13038---[nio-8080-exec-1]o.s.s.service.impl.CityServiceImpl:CityServiceImpl.findCityById():城市插入缓存>>City{id=12,provinceId=3,cityName='三亚',description='水好,天蓝'}
  2. 2017-04-1318:29:03.145INFO13038---[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 输出的日志:

  1. 12017-04-1318:29:52.248INFO13038---[nio-8080-exec-9]o.s.s.service.impl.CityServiceImpl:CityServiceImpl.deleteCity():从缓存中删除城市ID>>12

四、springboot-mybatis-redis 工程代码配置详解

这里,我强烈推荐 注解 的方式实现对象的缓存。但是这里为了更好说明缓存更新策略。下面讲讲工程代码的实现。

pom.xml 依赖配置:

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <projectxmlns="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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>springboot</groupId>
  6. <artifactId>springboot-mybatis-redis</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>springboot-mybatis-redis::整合Mybatis并使用Redis作为缓存</name>
  9. <!--SpringBoot启动父依赖-->
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>1.5.1.RELEASE</version>
  14. </parent>
  15. <properties>
  16. <mybatis-spring-boot>1.2.0</mybatis-spring-boot>
  17. <mysql-connector>5.1.39</mysql-connector>
  18. <spring-boot-starter-redis-version>1.3.2.RELEASE</spring-boot-starter-redis-version>
  19. </properties>
  20. <dependencies>
  21. <!--SpringBootReids依赖-->
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-redis</artifactId>
  25. <version>${spring-boot-starter-redis-version}</version>
  26. </dependency>
  27. <!--SpringBootWeb依赖-->
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-web</artifactId>
  31. </dependency>
  32. <!--SpringBootTest依赖-->
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. <!--SpringBootMybatis依赖-->
  39. <dependency>
  40. <groupId>org.mybatis.spring.boot</groupId>
  41. <artifactId>mybatis-spring-boot-starter</artifactId>
  42. <version>${mybatis-spring-boot}</version>
  43. </dependency>
  44. <!--MySQL连接驱动依赖-->
  45. <dependency>
  46. <groupId>mysql</groupId>
  47. <artifactId>mysql-connector-java</artifactId>
  48. <version>${mysql-connector}</version>
  49. </dependency>
  50. <!--Junit-->
  51. <dependency>
  52. <groupId>junit</groupId>
  53. <artifactId>junit</artifactId>
  54. <version>4.12</version>
  55. </dependency>
  56. </dependencies>
  57. </project>

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

在 application.properties 应用配置文件,增加 Redis 相关配置

  1. ##数据源配置
  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. ##Mybatis配置
  7. mybatis.typeAliasesPackage=org.spring.springboot.domain
  8. mybatis.mapperLocations=classpath:mapper/*.xml
  9. ##Redis配置
  10. ##Redis数据库索引(默认为0)
  11. spring.redis.database=0
  12. ##Redis服务器地址
  13. spring.redis.host=127.0.0.1
  14. ##Redis服务器连接端口
  15. spring.redis.port=6379
  16. ##Redis服务器连接密码(默认为空)
  17. spring.redis.password=
  18. ##连接池***连接数(使用负值表示没有限制)
  19. spring.redis.pool.max-active=8
  20. ##连接池***阻塞等待时间(使用负值表示没有限制)
  21. spring.redis.pool.max-wait=-1
  22. ##连接池中的***空闲连接
  23. spring.redis.pool.max-idle=8
  24. ##连接池中的最小空闲连接
  25. spring.redis.pool.min-idle=0
  26. ##连接超时时间(毫秒)
  27. 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 ,控制台会爆出以下异常:

  1. Serializable
  2. java.lang.IllegalArgumentException:DefaultSerializerrequiresaSerializablepayloadbutreceivedanobjectoftype

City.java 城市对象:

  1. packageorg.spring.springboot.domain;
  2. importjava.io.Serializable;
  3. /**
  4. *城市实体类
  5. *
  6. *Createdbybysocketon07/02/2017.
  7. */
  8. publicclassCityimplementsSerializable{
  9. privatestaticfinallongserialVersionUID=-1L;
  10. /**
  11. *城市编号
  12. */
  13. privateLongid;
  14. /**
  15. *省份编号
  16. */
  17. privateLongprovinceId;
  18. /**
  19. *城市名称
  20. */
  21. privateStringcityName;
  22. /**
  23. *描述
  24. */
  25. privateStringdescription;
  26. publicLonggetId(){
  27. returnid;
  28. }
  29. publicvoidsetId(Longid){
  30. this.id=id;
  31. }
  32. publicLonggetProvinceId(){
  33. returnprovinceId;
  34. }
  35. publicvoidsetProvinceId(LongprovinceId){
  36. this.provinceId=provinceId;
  37. }
  38. publicStringgetCityName(){
  39. returncityName;
  40. }
  41. publicvoidsetCityName(StringcityName){
  42. this.cityName=cityName;
  43. }
  44. publicStringgetDescription(){
  45. returndescription;
  46. }
  47. publicvoidsetDescription(Stringdescription){
  48. this.description=description;
  49. }
  50. @Override
  51. publicStringtoString(){
  52. return"City{"+
  53. "id="+id+
  54. ",provinceId="+provinceId+
  55. ",cityName='"+cityName+'\''+
  56. ",description='"+description+'\''+
  57. '}';
  58. }
  59. }

如果需要自定义序列化实现,只要实现 RedisSerializer 接口去实现即可,然后在使用 RedisTemplate.setValueSerializer 方法去设置你实现的序列化实现。

主要还是城市业务逻辑实现类 CityServiceImpl.java:

  1. packageorg.spring.springboot.service.impl;
  2. importorg.slf4j.Logger;
  3. importorg.slf4j.LoggerFactory;
  4. importorg.spring.springboot.dao.CityDao;
  5. importorg.spring.springboot.domain.City;
  6. importorg.spring.springboot.service.CityService;
  7. importorg.springframework.beans.factory.annotation.Autowired;
  8. importorg.springframework.data.redis.core.RedisTemplate;
  9. importorg.springframework.data.redis.core.StringRedisTemplate;
  10. importorg.springframework.data.redis.core.ValueOperations;
  11. importorg.springframework.stereotype.Service;
  12. importjava.util.List;
  13. importjava.util.concurrent.TimeUnit;
  14. /**
  15. *城市业务逻辑实现类
  16. *<p>
  17. *Createdbybysocketon07/02/2017.
  18. */
  19. @Service
  20. publicclassCityServiceImplimplementsCityService{
  21. privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(CityServiceImpl.class);
  22. @Autowired
  23. privateCityDaocityDao;
  24. @Autowired
  25. privateRedisTemplateredisTemplate;
  26. /**
  27. *获取城市逻辑:
  28. *如果缓存存在,从缓存中获取城市信息
  29. *如果缓存不存在,从DB中获取城市信息,然后插入缓存
  30. */
  31. publicCityfindCityById(Longid){
  32. //从缓存中获取城市信息
  33. Stringkey="city_"+id;
  34. ValueOperations<String,City>operations=redisTemplate.opsForValue();
  35. //缓存存在
  36. booleanhasKey=redisTemplate.hasKey(key);
  37. if(hasKey){
  38. Citycity=operations.get(key);
  39. LOGGER.info("CityServiceImpl.findCityById():从缓存中获取了城市>>"+city.toString());
  40. returncity;
  41. }
  42. //从DB中获取城市信息
  43. Citycity=cityDao.findById(id);
  44. //插入缓存
  45. operations.set(key,city,10,TimeUnit.SECONDS);
  46. LOGGER.info("CityServiceImpl.findCityById():城市插入缓存>>"+city.toString());
  47. returncity;
  48. }
  49. @Override
  50. publicLongsaveCity(Citycity){
  51. returncityDao.saveCity(city);
  52. }
  53. /**
  54. *更新城市逻辑:
  55. *如果缓存存在,删除
  56. *如果缓存不存在,不操作
  57. */
  58. @Override
  59. publicLongupdateCity(Citycity){
  60. Longret=cityDao.updateCity(city);
  61. //缓存存在,删除缓存
  62. Stringkey="city_"+city.getId();
  63. booleanhasKey=redisTemplate.hasKey(key);
  64. if(hasKey){
  65. redisTemplate.delete(key);
  66. LOGGER.info("CityServiceImpl.updateCity():从缓存中删除城市>>"+city.toString());
  67. }
  68. returnret;
  69. }
  70. @Override
  71. publicLongdeleteCity(Longid){
  72. Longret=cityDao.deleteCity(id);
  73. //缓存存在,删除缓存
  74. Stringkey="city_"+id;
  75. booleanhasKey=redisTemplate.hasKey(key);
  76. if(hasKey){
  77. redisTemplate.delete(key);
  78. LOGGER.info("CityServiceImpl.deleteCity():从缓存中删除城市ID>>"+id);
  79. }
  80. returnret;
  81. }
  82. }

首先这里注入了 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 缓存时,一个是缓存对象需要序列化,二个是缓存更新策略是如何的。

摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢!

©本文为清一色官方代发,观点仅代表作者本人,与清一色无关。清一色对文中陈述、观点判断保持中立,不对所包含内容的准确性、可靠性或完整性提供任何明示或暗示的保证。本文不作为投资理财建议,请读者仅作参考,并请自行承担全部责任。文中部分文字/图片/视频/音频等来源于网络,如侵犯到著作权人的权利,请与我们联系(微信/QQ:1074760229)。转载请注明出处:清一色财经

(0)
打赏 微信扫码打赏 微信扫码打赏 支付宝扫码打赏 支付宝扫码打赏
清一色的头像清一色管理团队
上一篇 2023年5月6日 09:27
下一篇 2023年5月6日 09:27

相关推荐

发表评论

登录后才能评论

联系我们

在线咨询:1643011589-QQbutton

手机:13798586780

QQ/微信:1074760229

QQ群:551893940

工作时间:工作日9:00-18:00,节假日休息

关注微信