您好,欢迎访问一九零五行业门户网

SpringBoot整合Redis缓存如何实现

springboot支持的缓存组件在springboot中,数据的缓存管理存储依赖于spring框架中cache相关的org.springframework.cache.cache和org.springframework.cache.cachemanager缓存管理器接口。
如果程序中没有定义类型为cachemanager的bean组件或者是名为cacheresolver的cacheresolver缓存解析器,springboot将尝试选择启用以下缓存组件(按照指定的顺序):
(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
上面按照springboot缓存组件的加载顺序,列举了springboot支持的9种缓存组件,在项目中添加某个缓存管理组件(例如redis)后,springboot项目会选择并启用对应的缓存管理器。如果在项目中同时添加了多个缓存组件,且没有指定缓存管理器或者缓存解析器(cachemanager或者cacheresolver),那么springboot会按照上述顺序在添加的多个缓存组件中优先启用排在前面的某个缓存组件进行缓存管理(例如,同时添加了couchbase和redis这两个缓存组件,那么优先启用couchbase组件)。
在上一篇文章 springboot缓存管理(一) 默认缓存管理 介绍的默认缓存管理中,我们搭建的项目没有添加任何缓存管理组件,但是依旧实现了缓存管理。这是因为开启缓存管理后,springboot会按照上述缓存组件顺序查找有效的缓存组件进行缓存管理,如果没有任何缓存组件,会默认使用最后一个simple缓存组件进行管理。simple缓存组件是springboot默认的缓存管理组件,它默认使用内存中的concurrentmap进行缓存存储,所以在没有添加任何第三方缓存组件的情况下,依旧可以实现内存中的缓存管理,但是不推荐这种缓存管理方式。
基于注解的redis缓存实现在 springboot缓存管理(一) 默认缓存管理 搭建的项目基础上引入redis缓存组件,使用基于注解的方式讲解springboot整合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作为自动配置类进行缓存相关的自动装配类(之前为默认的simplecacheconfiguration),容器中使用的缓存管理器变为了rediscachemanager(之前为默认为cachemanager),这个缓存管理器创建的cache为rediscache,进而操控redis进行数据的缓存。
(2)redis服务器连接配置
在项目的全局配置文件application.properties中添加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.hardy.springbootdatacache.service;import com.hardy.springbootdatacache.entity.comment;import com.hardy.springbootdatacache.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;/** * @author: hardyyao * @date: 2021/6/19 */@servicepublic class commentservice { @autowiredprivate commentrepository commentrepository;/** * 根据评论id查询评论 * @cacheable:将该方法的查询结果comment存放在springboot默认缓存中 * cachenames:起一个缓存命名空间,对应缓存唯一标识 * @param id * @return */@cacheable(cachenames = "comment", unless = "#result==null")public comment findcommentbyid(integer id){ optional<comment> comment = commentrepository.findbyid(id);if(comment.ispresent()){ comment comment1 = comment.get();return comment1; }return null; }/** * 更新评论 * @param comment * @return */@cacheput(cachenames = "comment",key = "#result.id")public comment updatecomment(comment comment) { commentrepository.updatecomment(comment.getauthor(), comment.getaid());return comment; }/** * 删除评论 * @param comment_id */@cacheevict(cachenames = "comment")public void deletecomment(int comment_id) { commentrepository.deletebyid(comment_id); }}
在上述代码中,使用了@cacheable、@cacheput、@cacheevict注解在数据查询、数据更新及数据删除方法上进行了缓存管理。
其中,查询缓存@cacheable注解中没有标记key值,将会使用默认参数值comment_id作为key进行数据保存,在进行缓存更新时必须使用同样的的key;同样,在使用查询缓存@cacheable注解中,定义了 unless= “#result==null” 表示查询结果为空则不进行缓存。
(4)在commentcontroller类中新增两个接口
新增更新和删除的接口:
package com.hardy.springbootdatacache.controller;import com.hardy.springbootdatacache.entity.comment;import com.hardy.springbootdatacache.service.commentservice;import org.springframework.beans.factory.annotation.autowired;import org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.bind.annotation.restcontroller;/** * @author: hardyyao * @date: 2021/6/19 */@restcontrollerpublic class commentcontroller { @autowiredprivate commentservice commentservice; @requestmapping(value = "/findcommentbyid")public comment findcommentbyid(integer id){ comment comment = commentservice.findcommentbyid(id);return comment; } @requestmapping(value = "/updatecomment")public comment updatecomment(comment comment){ comment oldcomment = commentservice.findcommentbyid(comment.getid()); oldcomment.setauthor(comment.getauthor()); comment comment1 = commentservice.updatecomment(oldcomment);return comment1; } @requestmapping(value = "/deletecomment")public void deletecomment(integer id){ commentservice.deletecomment(id); }}
(5)基于注解的redis查询缓存测试
在浏览器中输入:http://localhost:8080/findcommentbyid?id=1 进行访问:
页面报错了,查看控制台信息:
根据报错信息可知:查询用户评论信息comment时执行了相应的sql语句,但是在进行缓存存储时出现了illegalargumentexception非法参数异常,提示信息要求对应的comment实体类必须实现序列化(defaultserializer requires a serializable payload but received an object of type [com.hardy.springbootdatacache.entity.comment])。
(6)将缓存对象实现序列化
(7)重启项目测试查询缓存
在浏览器中输入:http://localhost:8080/findcommentbyid?id=1 进行访问(连续访问三次):
打开redis客户端可视化工具redis desktop manager,连接本地启用的redis服务,查看具体的数据缓存效果:
执行findbyid()方法查询出的用户评论信息comment正确存储到了redis缓存库中名为comment的名称空间下。
其中缓存数据的唯一标识key值是以“名称空间comment::+参数值(comment::1)”的字符串形式体现的,而value值则是经过jdk默认序列格式化后的hex格式存储。这种jdk默认序列格式化后的数据显然不方便缓存数据的可视化查看和管理,所以在实际开发中,通常会自定义数据的序列化格式,这方面的内容在后面会介绍。
(8)基于注解的redis缓存更新测试
先通过浏览器访问:http://localhost:8080/updatecomment?id=1&author=hardy;
接着在访问:http://localhost:8080/findcommentbyid?id=1,查看浏览器返回信息及控制台打印信息:
可以看到,执行updatecomment()更新id为1的数据时执行了一条更新的sql语句,后续调用findbyid()方法查询id为1的用户评论信息时没有再次执行查询的sql语句,且浏览器返回了更新后的正确结果,这说明@cacheput缓存更新配置成功。
(9)基于注解的redis缓存删除测试
通过浏览器访问:http://localhost:8080/deletecomment?id=1 和 http://localhost:8080/findcommentbyid?id=1
执行deletecomment()方法删除id为1的数据后查询结果为空,查看redis缓存数据库:
可以看到之前存储的comment相关数据被删除掉了,这表明@cacheevict注解缓存删除成功实现。
通过上面的案例可以看出:使用基于注解的redis缓存实现只需要添加redis依赖、并使用几个注解在对应的方法上,就可以实现对数据的缓存管理。
另外,还可以在springboot全局配置文件中配置redis有效期,示例代码如下:
# 对基于注解的redis缓存数据统一设置有效期为1分钟,单位毫秒spring.cache.redis.time-to-live=60000
上述代码中,在springboot全局配置文件中添加了“spring.cache.redis.time-to-live”属性统一设置redis数据的有效期(单位为毫秒),但这种方式不够灵活,因此一般不用。
基于api的redis缓存实现在springboot整合redis缓存实现中,除了基于注解形式的redis缓存形式外,还有一种开发中更常用的方式——基于api的redis缓存实现。这种基于api的redis缓存实现,需要在某种业务需求下通过redis提供的api调用相关方法实现数据缓存管理。同时,这种方法还可以手动管理缓存的有效期。
下面,通过redis api的方式讲解springboot整合redis缓存的具体实现。
(1)使用redis api进行业务数据缓存管理
在 com.hardy.springbootdatacache.service 包下新建一个 apicommentservice:
package com.hardy.springbootdatacache.service;import com.hardy.springbootdatacache.entity.comment;import com.hardy.springbootdatacache.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;/** * @author: hardyyao * @date: 2021/6/19 */@servicepublic class apicommentservice { @autowiredprivate commentrepository commentrepository; @autowiredprivate redistemplate redistemplate;/** * 根据评论id查询评论 * @param id * @return */public comment findcommentbyid(integer id){// 先查redis缓存object o = redistemplate.opsforvalue().get("comment_" + id);if (o != null) {return (comment) o; } else {// 如果缓存中没有,则从数据库查询optional<comment> dbcomment = commentrepository.findbyid(id);if (dbcomment.ispresent()) { comment rediscomment = dbcomment.get();// 将查询结果存储到缓存中,并设置有效期为1天redistemplate.opsforvalue().set("comment_"+id, rediscomment,1, timeunit.days);return rediscomment; } else {return null; } } }/** * 更新评论 * @param comment * @return */public comment updatecomment(comment comment) { commentrepository.updatecomment(comment.getauthor(), comment.getid());// 更新数据库数据后进行缓存更新redistemplate.opsforvalue().set("comment_" + comment.getid(), comment);return comment; }/** * 删除评论 * @param comment_id */public void deletecomment(int comment_id) { commentrepository.deletebyid(comment_id);// 删除数据库数据后进行缓存删除redistemplate.delete("comment_" + comment_id); }}
(2)编写web访问层apicommentcontroller
package com.hardy.springbootdatacache.controller;import com.hardy.springbootdatacache.entity.comment;import com.hardy.springbootdatacache.service.apicommentservice;import org.springframework.beans.factory.annotation.autowired;import org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.bind.annotation.restcontroller;/** * @author: hardyyao * @date: 2021/6/19 */@restcontroller@requestmapping("api") // 改变请求路径public class apicommentcontroller { @autowiredprivate apicommentservice apicommentservice; @requestmapping(value = "/findcommentbyid")public comment findcommentbyid(integer id){ comment comment = apicommentservice.findcommentbyid(id);return comment; } @requestmapping(value = "/updatecomment")public comment updatecomment(comment comment){ comment oldcomment = apicommentservice.findcommentbyid(comment.getid()); oldcomment.setauthor(comment.getauthor()); comment comment1 = apicommentservice.updatecomment(oldcomment);return comment1; } @requestmapping(value = "/deletecomment")public void deletecomment(integer id){ apicommentservice.deletecomment(id); }}
(3)测试基于api的redis缓存实现
输入:http://localhost:8080/api/findcommentbyid?id=2(连续输入三次)、http://localhost:8080/api/updatecomment?id=2&author=hardy、http://localhost:8080/deletecomment?id=2进行访问:
查看控制台消息及redis数据库:
基于api的redis缓存实现的相关配置:基于api的redis缓存实现不需要@enablecaching注解开启基于注解的缓存支持,所以这里可以选择将添加在项目启动类上的@enablecaching注解进行删除或者注释,不会影响项目的功能实现。
以上就是springboot整合redis缓存如何实现的详细内容。
其它类似信息

推荐信息