当前位置:首页 > 文章列表 > 数据库 > Redis > 聊聊Spring Boot+Redis实现缓存的操作

聊聊Spring Boot+Redis实现缓存的操作

来源:51cto 2023-02-23 21:51:46 0浏览 收藏

今天golang学习网给大家带来了《聊聊Spring Boot+Redis实现缓存的操作》,其中涉及到的知识点包括操作、Redis、Spring Boo等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

一、缓存的应用场景

二、更新缓存的策略

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

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

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

下面开始运行工程步骤(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

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

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

pom.xml 依赖配置:

<?xml &nbsp;version="1.0"&nbsp;encoding="UTF-8"?> 
<project> 
    <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> 
    <!--&nbsp;Spring&nbsp;Boot&nbsp;启动父依赖&nbsp;--> 
    <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> 
        <!--&nbsp;Spring&nbsp;Boot&nbsp;Reids&nbsp;依赖&nbsp;--> 
        <dependency> 
            <groupid>org.springframework.boot</groupid> 
            <artifactid>spring-boot-starter-redis</artifactid> 
            <version>${spring-boot-starter-redis-version}</version> 
        </dependency> 
        <!--&nbsp;Spring&nbsp;Boot&nbsp;Web&nbsp;依赖&nbsp;--> 
        <dependency> 
            <groupid>org.springframework.boot</groupid> 
            <artifactid>spring-boot-starter-web</artifactid> 
        </dependency> 
        <!--&nbsp;Spring&nbsp;Boot&nbsp;Test&nbsp;依赖&nbsp;--> 
        <dependency> 
            <groupid>org.springframework.boot</groupid> 
            <artifactid>spring-boot-starter-test</artifactid> 
            <scope>test</scope> 
        </dependency> 
        <!--&nbsp;Spring&nbsp;Boot&nbsp;Mybatis&nbsp;依赖&nbsp;--> 
        <dependency> 
            <groupid>org.mybatis.spring.boot</groupid> 
            <artifactid>mybatis-spring-boot-starter</artifactid> 
            <version>${mybatis-spring-boot}</version> 
        </dependency> 
        <!--&nbsp;MySQL&nbsp;连接驱动依赖&nbsp;--> 
        <dependency> 
            <groupid>mysql</groupid> 
            <artifactid>mysql-connector-java</artifactid> 
            <version>${mysql-connector}</version> 
        </dependency> 
        <!--&nbsp;Junit&nbsp;--> 
        <dependency> 
            <groupid>junit</groupid> 
            <artifactid>junit</artifactid> 
            <version>4.12</version> 
        </dependency> 
    </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> 
 * 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> 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;</string></p>

首先这里注入了 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 」欢迎转载,保留摘要,谢谢!

 

到这里,我们也就讲完了《聊聊Spring Boot+Redis实现缓存的操作》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于redis的知识点!

版本声明
本文转载于:51cto 如有侵犯,请联系study_golang@163.com删除
最全面!搞定Redis备份、容灾及高可用实战最全面!搞定Redis备份、容灾及高可用实战
上一篇
最全面!搞定Redis备份、容灾及高可用实战
汇总Redis Cluster迁移遇到的运维问题(附解决方案)
下一篇
汇总Redis Cluster迁移遇到的运维问题(附解决方案)
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 茅茅虫AIGC检测:精准识别AI生成内容,保障学术诚信
    茅茅虫AIGC检测
    茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
    25次使用
  • 赛林匹克平台:科技赛事聚合,赋能AI、算力、量子计算创新
    赛林匹克平台(Challympics)
    探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
    50次使用
  • SEO  笔格AIPPT:AI智能PPT制作,免费生成,高效演示
    笔格AIPPT
    SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
    58次使用
  • 稿定PPT:在线AI演示设计,高效PPT制作工具
    稿定PPT
    告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
    54次使用
  • Suno苏诺中文版:AI音乐创作平台,人人都是音乐家
    Suno苏诺中文版
    探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
    60次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码