广告
返回顶部
首页 > 资讯 > 精选 >Spring Boot中怎么利用Redis 实现缓存操作
  • 210
分享到

Spring Boot中怎么利用Redis 实现缓存操作

2023-06-17 04:06:09 210人浏览 八月长安
摘要

这期内容当中小编将会给大家带来有关Spring Boot中怎么利用Redis 实现缓存操作,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。一、缓存的应用场景二、更新缓存的策略三、运行 springboot-

这期内容当中小编将会给大家带来有关Spring Boot中怎么利用Redis 实现缓存操作,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

一、缓存的应用场景

二、更新缓存的策略

三、运行 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:

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 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 依赖 -->         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-web</artifactId>         </dependency>           <!-- Spring Boot Test 依赖 -->         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-test</artifactId>             <scope>test</scope>         </dependency>           <!-- Spring Boot Mybatis 依赖 -->         <dependency>             <groupId>org.mybatis.spring.boot</groupId>             <artifactId>mybatis-spring-boot-starter</artifactId>             <version>${mybatis-spring-boot}</version>         </dependency>           <!-- Mysql 连接驱动依赖 -->         <dependency>             <groupId>mysql</groupId>             <artifactId>mysql-connector-java</artifactId>             <version>${mysql-connector}</version>         </dependency>           <!-- Junit -->         <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 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;    @Service public class CityServiceImpl implements CityService {       private static final Logger LOGGER = LoggerFactory.getLogger(CityServiceImpl.class);       @Autowired     private CityDao cityDao;       @Autowired     private RedisTemplate redisTemplate;            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;     }       @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;     }   }

首先这里注入了 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 更新城市逻辑:

如果缓存存在,删除

如果缓存不存在,不操作

上述就是小编为大家分享的Spring Boot中怎么利用Redis 实现缓存操作了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注编程网精选频道。

--结束END--

本文标题: Spring Boot中怎么利用Redis 实现缓存操作

本文链接: https://www.lsjlt.com/news/287068.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring Boot中怎么利用Redis 实现缓存操作
    这期内容当中小编将会给大家带来有关Spring Boot中怎么利用Redis 实现缓存操作,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。一、缓存的应用场景二、更新缓存的策略三、运行 springboot-...
    99+
    2023-06-17
  • Redis如何实现在Spring Boot中做缓存
    Redis如何实现在Spring Boot中做缓存?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。1、创建UserServicepublic interface UserSe...
    99+
    2023-05-31
    springboot redis edi
  • Spring Boot中怎么使用集中式缓存Redis
    本篇内容介绍了“Spring Boot中怎么使用集中式缓存Redis”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!动手试试User实体的定义...
    99+
    2023-06-27
  • 详解Spring Boot使用redis实现数据缓存
    基于spring Boot 1.5.2.RELEASE版本,一方面验证与Redis的集成方法,另外了解使用方法。集成方法配置依赖修改pom.xml,增加如下内容。 <dependency> <groupId>...
    99+
    2023-05-31
    spring boot redis
  • 怎么在Spring Boot中利用Redis实现session共享
    本篇文章给大家分享的是有关怎么在Spring Boot中利用Redis实现session共享,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。引入spring-boot-start...
    99+
    2023-05-30
    springboot session redis
  • Spring Boot中怎么利用Redis实现分布式锁
    Spring Boot中怎么利用Redis实现分布式锁,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。分布式锁介绍Spring Boot 实现 Redis 分布式锁在 sprin...
    99+
    2023-06-16
  • 在Spring Boot中使用注解如何实现Redis 缓存
    在Spring Boot中使用注解如何实现Redis 缓存?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。一、创建 Caching 配置类RedisKeys.Javapackag...
    99+
    2023-05-31
    springboot redis 注解
  • Redis通过在Spring Boot项目中使用实现集中式缓存
    这篇文章将为大家详细讲解有关Redis通过在Spring Boot项目中使用实现集中式缓存,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。 利用Spring Initializr来新建一个sp...
    99+
    2023-05-31
    springboot 集中 redis
  • SpringBoot怎么整合Spring Cache实现Redis缓存
    今天小编给大家分享一下SpringBoot怎么整合Spring Cache实现Redis缓存的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下...
    99+
    2023-07-02
  • Spring Boot如何利用拦截器加缓存完成接口防刷操作
    目录为什么需要接口防刷技术解析主要代码测试结果总结为什么需要接口防刷 为了减缓服务器压力,将服务器资源留待给有价值的请求,防止恶意访问,一般的程序都会有接口防刷设置,接下来介绍一种简...
    99+
    2022-11-13
  • thinkphp中怎么利用redis实现秒杀缓存功能
    thinkphp中怎么利用redis实现秒杀缓存功能,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。1,安装redis,根据自己的php版本安装对应的redis扩...
    99+
    2023-06-19
  • spring boot 中的hibernate怎么使用ehcache 2.x实现二级缓存
    今天就跟大家聊聊有关spring boot 中的hibernate怎么使用ehcache 2.x实现二级缓存,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。项目依赖<depend...
    99+
    2023-05-31
    springboot hibernate ehcache 2.x
  • Spring boot中mybatis的二级缓存怎么使用Redis集群进行替换
    这篇文章给大家介绍Spring boot中mybatis的二级缓存怎么使用Redis集群进行替换,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。1 . pom.xml添加相关依赖<parent> <...
    99+
    2023-05-31
    springboot mybatis redis
  • SpringBoot2 中怎么利用Redis数据库实现缓存管理
    SpringBoot2 中怎么利用Redis数据库实现缓存管理,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。一、Redis简介Spring Boot中除了对常用...
    99+
    2023-06-02
  • Spring Boot中怎么利用MybatisPlus实现逆向工程
    这篇文章将为大家详细讲解有关Spring Boot中怎么利用MybatisPlus实现逆向工程,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。 一、创建表  我们先创建数据库表:sys_log...
    99+
    2023-06-20
  • Spring Boot 中怎么利用JSR303 实现参数验证
    今天就跟大家聊聊有关Spring Boot 中怎么利用JSR303 实现参数验证,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。Bean Validation 规范内嵌的约束注解实例基...
    99+
    2023-06-05
  • Spring Boot怎么利用拦截器加缓存完成接口防刷
    小编给大家分享一下Spring Boot怎么利用拦截器加缓存完成接口防刷,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!为什么需要接口防刷为了减缓服务器压...
    99+
    2023-06-29
  • odoo中怎么使用redis实现缓存
    本篇内容主要讲解“odoo中怎么使用redis实现缓存”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“odoo中怎么使用redis实现缓存”吧!Odoo中使用Redis实现缓存可以提高系统性能,避...
    99+
    2023-07-05
  • Spring项目中使用Cache Redis实现数据缓存
    目录Spring项目中实现数据缓存一、Spring Cache + Redis 介绍二、项目中集成1. 引入依赖2. 添加 redis 配置类3. 配置文件增加 redis 配置4....
    99+
    2022-11-13
  • Spring Boot中怎么利用JUnit 5实现单元测试
    这篇文章给大家介绍Spring Boot中怎么利用JUnit 5实现单元测试,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。1. 忽略测试用例执行JUnit 4:@Test  @Ignore ...
    99+
    2023-06-16
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作