广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot详解整合Redis缓存方法
  • 823
分享到

SpringBoot详解整合Redis缓存方法

2024-04-02 19:04:59 823人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录1、Spring Boot支持的缓存组件2、基于注解的Redis缓存实现3、基于api的Redis缓存实现1、spring Boot支持的缓存组件 在Spring Boot中,数

1、spring Boot支持的缓存组件

在Spring Boot中,数据的缓存管理存储依赖于Spring框架中cache相关的org.springframework.cache.Cache和org.springframework.cache.CacheManager缓存管理器接口。

如果程序中没有定义类型为CacheManager的Bean组件或者是名为cacheResolver的CacheResolver缓存解析器,Spring Boot将尝试选择并启用以下缓存组件(按照指定的顺序):

(1)Generic

(2)JCache (jsR-107) (EhCache 3、Hazelcast、Infinispan等)

(3)EhCache 2.x

(4)Hazelcast

(5)Infinispan

(6)CoucHBase

(7)Redis

(8)Caffeine

(9)Simple

上面按照Spring Boot缓存组件的加载顺序,列举了支持的9种缓存组件,在项目中添加某个缓存管理组件(例如Redis)后,Spring Boot项目会选择并启用对应的缓存管理器。如果项目中同时添加了多个缓存组件,且没有指定缓存管理器或者缓存解析器(CacheManager或者cacheResolver),那么Spring Boot会按照上述顺序在添加的多个缓存中优先启用指定的缓存组件进行缓存管理。

刚刚讲解的Spring Boot默认缓存管理中,没有添加任何缓存管理组件能实现缓存管理。这是因为开启缓存管理后,Spring Boot会按照上述列表顺序查找有效的缓存组件进行缓存管理,如果没有任何缓存组件,会默认使用最后一个Simple缓存组件进行管理。Simple缓存组件是Spring Boot默认的缓存管理组件,它默认使用内存中的ConcurrentMap进行缓存存储,所以在没有添加任何第三方缓存组件的情况下,可以实现内存中的缓存管理,但是我们不推荐使用这种缓存管理方式

2、基于注解的Redis缓存实现

在Spring Boot默认缓存管理的基础上引入Redis缓存组件,使用基于注解的方式讲解Spring Boot整合Redis缓存的具体实现

(1)添加Spring Data Redis依赖启动器。在pom.xml文件中添加Spring Data Redis依赖启动器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

当我们添加进redis相关的启动器之后, SpringBoot会使用RedisCacheConfigratioin 当做生效的自动配置类进行缓存相关的自动装配,容器中使用的缓存管理器是RedisCacheManager , 这个缓存管理器创建的Cache为 RedisCache , 进而操控redis进行数据的缓存

(2)Redis服务连接配置

# Redis服务地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.passWord=

(3)对CommentService类中的方法进行修改使用@Cacheable、@CachePut、@CacheEvict三个注解定制缓存管理,分别进行缓存存储、缓存更新和缓存删除的演示

package com.laGou.service;
import com.lagou.pojo.Comment;
import com.lagou.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;
    
    @Cacheable(cacheNames = "comment", unless = "#result==null")
    public Comment findCommentById(Integer id) {
        Optional<Comment> byId = commentRepository.findById(id);
        if (byId.isPresent()) {
            Comment comment = byId.get();
            return comment;
        }
        return null;
    }
    // 更新方法
    @CachePut(cacheNames = "comment", key = "#result.id")
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        return comment;
    }
    // 删除方法
    @CacheEvict(cacheNames = "comment")
    public void deleteComment(Integer id) {
        commentRepository.deleteById(id);
    }
}

以上 使用@Cacheable、@CachePut、@CacheEvict注解在数据查询、更新和删除方法上进行了缓存管理。

其中,查询缓存@Cacheable注解中没有标记key值,将会使用默认参数值comment_id作为key进行数据保存,在进行缓存更新时必须使用同样的key;同时在查询缓存@Cacheable注解中,定义了“unless = "#result==null"”表示查询结果为空不进行缓存

控制层

package com.lagou.controller;
import com.lagou.pojo.Comment;
import com.lagou.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.WEB.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CommentController {
    @Autowired
    private CommentService commentService;
    @RequestMapping( "/findCommentById")
    public Comment findCommentById(Integer id) {
        Comment comment = commentService.findCommentById(id);
        return comment;
    }
    @RequestMapping(value = "/updateComment")
    public Comment updateComment(Comment comment) {
        Comment commentById = commentService.findCommentById(comment.getId());
        commentById.setAuthor(comment.getAuthor());
        return commentService.updateComment(commentById);
    }
    @RequestMapping(value = "/deleteComment")
    public void deleteComment(Integer id) {
        commentService.deleteComment(id);
    }
}

(4) 基于注解的Redis查询缓存测试

可以看出,查询用户评论信息Comment时执行了相应的sql语句,但是在进行缓存存储时出现了IllegalArgumentException非法参数异常,提示信息要求对应Comment实体类必须实现序列化(“DefaultSerializer requires a Serializable payload but received an object of type”)。

(5)将缓存对象实现序列化。

(6)再次启动测试

访问“Http://localhost:8080/findCommentById?id=1”查询id为1的用户评论信息,并重复刷新浏览器查询同一条数据信息,查询结果

查看控制台打印的SQL查询语句

还可以打开Redis客户端可视化管理工具Redis Desktop Manager连接本地启用的Redis服务,查看具体的数据缓存效果

执行findById()方法查询出的用户评论信息Comment正确存储到了Redis缓存库中名为comment的名称空间下。其中缓存数据的唯一标识key值是以“名称空间comment::+参数值(comment::1)”的字符串形式体现的,而value值则是经过jdk默认序列格式化后的HEX格式存储。这种JDK默认序列格式化后的数据显然不方便缓存数据的可视化查看和管理,所以在实际开发中,通常会自定义数据的序列化格式

(7) 基于注解的Redis缓存更新测试。

先通过浏览器访问“http://localhost:8080/updateComment/1/shitou”更新id为1的评论作者名为shitou;

接着,继续访问“http://localhost:8080/findCommentById?id=1”查询id为1的用户评论信息

可以看出,执行updateComment()方法更新id为1的数据时执行了一条更新SQL语句,后续调用findById()方法查询id为1的用户评论信息时没有执行查询SQL语句,且浏览器正确返回了更新后的结果,表明@CachePut缓存更新配置成功

(8)基于注解的Redis缓存删除测试

通过浏览器访问“http://localhost:8080/deleteComment?id=1”删除id为1的用户评论信息;

执行deleteComment()方法删除id为1的数据后查询结果为空,之前存储在Redis数据库的comment相关数据也被删除,表明@CacheEvict缓存删除成功实现

通过上面的案例可以看出,使用基于注解的Redis缓存实现只需要添加Redis依赖并使用几个注解可以实现对数据的缓存管理。另外,还可以在Spring Boot全局配置文件中配置Redis有效期,示例代码如下:

# 对基于注解的Redis缓存数据统一设置有效期为1分钟,单位毫秒
spring.cache.redis.time-to-live=60000

上述代码中,在Spring Boot全局配置文件中添加了“spring.cache.redis.time-to-live”属性统一配置Redis数据的有效期(单位为毫秒),但这种方式相对来说不够灵活

3、基于API的Redis缓存实现

在Spring Boot整合Redis缓存实现中,除了基于注解形式的Redis缓存实现外,还有一种开发中常用的方式——基于API的Redis缓存实现。这种基于API的Redis缓存实现,需要在某种业务需求下通过Redis提供的API调用相关方法实现数据缓存管理;同时,这种方法还可以手动管理缓存的有效期。

下面,通过Redis API的方式讲解Spring Boot整合Redis缓存的具体实现

(1)使用Redis API进行业务数据缓存管理。在com.lagou.service包下编写一个进行业务处理的类ApiCommentService

package com.lagou.service;
import com.lagou.pojo.Comment;
import com.lagou.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@Service
public class ApiCommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    // 使用API方式进行缓存,先去缓存中查找,缓存中有,直接返回;没有查询数据库
    public Comment findCommentById(Integer id) {
        Object o = redisTemplate.opsForValue().get("comment_" + id);
        if (o != null) {
            return (Comment) o; // 查询到数据
        } else {
            // 缓存中没有,从数据库中查询
            Optional<Comment> byId = commentRepository.findById(id);
            if (byId.isPresent()) {
                Comment comment = byId.get();
                // 将查询结果存入到缓存中,同时还可以设置有效期
                redisTemplate.opsForValue().set("comment_" + id, comment, 1, TimeUnit.DAYS); // 过期时间为一天
                return comment;
            }
        }
        return null;
    }
    // 更新方法
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        // 将更新数据进行缓存更新
        redisTemplate.opsForValue().set("comment_" + comment.getId(), comment, 1, TimeUnit.DAYS);
        return comment;
    }
    // 删除方法
    public void deleteComment(Integer id) {
        commentRepository.deleteById(id);
        redisTemplate.delete("comment_" + id);
    }
}

(2)编写Web访问层Controller文件

package com.lagou.controller;
import com.lagou.pojo.Comment;
import com.lagou.service.ApiCommentService;
import com.lagou.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiCommentController {
    @Autowired
    private ApiCommentService commentService;
    @RequestMapping( "/findCommentById")
    public Comment findCommentById(Integer id) {
        Comment comment = commentService.findCommentById(id);
        return comment;
    }
    @RequestMapping(value = "/updateComment")
    public Comment updateComment(Comment comment) {
        Comment commentById = commentService.findCommentById(comment.getId());
        commentById.setAuthor(comment.getAuthor());
        return commentService.updateComment(commentById);
    }
    @RequestMapping(value = "/deleteComment")
    public void deleteComment(Integer id) {
        commentService.deleteComment(id);
    }
}

基于API的Redis缓存实现的相关配置。基于API的Redis缓存实现不需要@EnableCaching注解开启基于注解的缓存支持,所以这里可以选择将添加在项目启动类上的@EnableCaching进行删除或者注释

到此这篇关于SpringBoot详解整合Redis缓存方法的文章就介绍到这了,更多相关SpringBoot Redis缓存内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot详解整合Redis缓存方法

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

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

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

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

下载Word文档
猜你喜欢
  • SpringBoot详解整合Redis缓存方法
    目录1、Spring Boot支持的缓存组件2、基于注解的Redis缓存实现3、基于API的Redis缓存实现1、Spring Boot支持的缓存组件 在Spring Boot中,数...
    99+
    2022-11-13
  • springboot缓存之redis整合的方法
    今天小编给大家分享一下springboot缓存之redis整合的方法的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。默认使用的...
    99+
    2023-06-08
  • SpringBoot详解如何整合Redis缓存验证码
    目录1、简介2、介绍3、前期配置3.1、坐标导入3.2、配置文件3.3、配置类4、Java操作Redis1、简介 Redis is an open source (BSD licen...
    99+
    2022-11-13
  • 介绍SpringBoot 整合 Redis 缓存
    无法支撑这么大的数据访问量,redis使用的时候可以单独利用客户端引入jar包操作即可,实际项目中都是和框架进行整合的比较多,此处演示利用springboot整合1.首先导入使用Maven导入jar包...
    99+
    2023-06-02
  • SpringBoot怎么整合Redis缓存
    SpringBoot怎么整合Redis缓存?针对这个问题,今天小编总结了这篇文章,希望能帮助更多想解决这个问题的朋友找到更加简单易行的办法。1、引入缓存依赖<dependency> &...
    99+
    2022-10-18
  • SpringBoot详解整合Spring Cache实现Redis缓存流程
    目录1、简介2、常用注解2.1、@EnableCaching2.2、@Cacheable2.3、@CachePut2.4、@CacheEvict3、使用Redis当作缓存产品3.1、...
    99+
    2022-11-13
  • SpringBoot整合Redis入门之缓存数据的方法
    目录前言为什么要使用Redis呢?相关依赖配置数据库实体类RedisConfigMapperService接口Service实现类测试RedisController前言 Redis是...
    99+
    2022-11-12
  • SpringBoot怎样整合redis的缓存?
    这篇文章为大家带来有关SpringBoot整合redis缓存的详细介绍。大部分知识点都是大家经常用到的,为此分享给大家做个参考。一起跟随小编过来看看吧。开启远程访问:找到redis中的redis.conf文...
    99+
    2022-10-18
  • SpringBoot整合Canal方法详解
    目录pom.xml 添加 canal.client 依赖业务功能处理简单连接程序单次获取数据循环获取数据解析 storeValue 值不同的类型进行不同的处理一次性获取多条数据ack...
    99+
    2022-12-21
    SpringBoot整合Canal SpringBoot Canal
  • SpringBoot整合Quartz方法详解
    目录基础依赖cron表达式通用内存任务工程启动时就在执行的任务手动控制某个任务定义任务借助Web-Controller去开启该任务持久化配置Quartz为我们准备了sql数据表暂停任...
    99+
    2023-05-17
    SpringBoot整合Quartz SpringBoot Quartz
  • SpringBoot怎么整合Redis缓存验证码
    今天小编给大家分享一下SpringBoot怎么整合Redis缓存验证码的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。1、简介...
    99+
    2023-07-02
  • 详解redis与spring的整合(使用缓存)
    1、实现目标通过redis缓存数据。(目的不是加快查询的速度,而是减少数据库的负担)  2、所需jar包注意:jdies和commons-pool两个jar的版本是有对应关系的,注意引入jar包是要配对使用,否则将会报错。因为commons...
    99+
    2023-05-31
    spring redis
  • springBoot整合rabbitMQ的方法详解
    引入pom <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave...
    99+
    2022-11-12
  • SpringBoot整合mybatis的方法详解
    目录1 依赖配置2 使用2.1 SpringBoot配置整合mybatis:2.2 SpringBoot注解整合mybatis:2.3 在配置类上增加@MapperScan注解,扫描...
    99+
    2022-11-13
  • springboot整合mybatisplus的方法详解
    目录POM:application.yaml:POJO:mapper接口:包扫描:测试:总结POM: <dependency> <groupId>com....
    99+
    2022-11-13
  • SpringBoot整合Shiro的方法详解
    目录1.Shito简介1.1 什么是shiro1.2 有哪些功能2.QuickStart3.SpringBoot中集成1.导入shiro相关依赖2.自定义UserRealm3.定义s...
    99+
    2022-11-13
  • Springboot框架整合添加redis缓存功能
    目录一:安装Redis二:添加Redis依赖三:添加Redis配置信息四:创建RedisConfigurer五:创建Redis常用方法六:接口测试Hello大家好,本章我们添加red...
    99+
    2022-11-12
  • SpringBoot怎么整合Spring Cache实现Redis缓存
    今天小编给大家分享一下SpringBoot怎么整合Spring Cache实现Redis缓存的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下...
    99+
    2023-07-02
  • Springboot详解缓存redis实现定时过期方法
    目录前言添加依赖添加配置常规缓存开启缓存设置缓存空间设置缓存增加设置缓存过期时间总结后记前言 使用redis进行缓存数据,是目前比较常用的缓存解决方案。常用的缓存形式有一下几种: 1...
    99+
    2022-11-13
  • Springboot redis整合配置的方法
    本文小编为大家详细介绍“Springboot redis整合配置的方法”,内容详细,步骤清晰,细节处理妥当,希望这篇“Springboot redis整合配置的方法”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。1...
    99+
    2023-06-19
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作