系列十、SpringBoot + MyBatis + Redis实现分布式缓存(基于注解方式)

一、概述

        上篇文章 系列九、SpringBoot + MyBatis + Redis实现分布式缓存 介绍了基于xml方式实现分布式缓存的效果,当前大家使用的技术栈基本是springboot+各种框架的组合,而springboot显著的一个特点就是去xml配置,那么在无xml配置的情形下,又该如何实现分布式缓存呢?请看下面的代码实战

二、代码实战

2.1、分布式缓存相关的注解

        基于注解方式的分布式缓存,主要涉及到如下几个注解:

        (1)@EnableCaching:一般标注在配置类上,表示开启Spring的缓存,如果不加此注解的话Spring自带的缓存将不生效;

        (2)@CacheConfig(cacheNames = "xxx"):一般标注在service类上,用于配置cache的名字,建议以当前service类的全路径名作为cache的名字;

        (3)@Cacheable:一般标识在service层的查询方法上,表示将一个方法的返回值缓存起来,  默认情况下,缓存的key就是方法的参数,缓存的value就是方法的返回值,如果查询 方法无参数,则会使用默认的key,即SimpleKey [];

        (4)@CachePut(key = "#department.id"):一般加在service层的更新方法上(update),当数据库中的数据更新后,缓存中的数据也要跟着更新,使用此注解,可以将方法的返回值 自动更新到已经存在的key上

        (5)@CacheEvict:一般加在service层的删除方法上,当数据库中的数据删除后,相关的缓存也会被删除,使用该注解的时候,也可以配置按照某种条件删除(某种条件:@CacheEvict注解中的条件,例如:value、cacheNames、key、keyGenerator...)

2.2、项目概览

2.3、pom

<dependencies><!-- springboot --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId></dependency><!-- 数据源 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.1</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- 工具 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.30</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.21</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-collections4</artifactId><version>4.4</version></dependency><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>2.0.25</version></dependency></dependencies>

2.4、yml

server:port: 9999spring:redis:host: port: 6379database: 0password: 123456datasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/20231018_redis?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMTusername: rootpassword: 123456mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: org.stat.entity.modelconfiguration:map-underscore-to-camel-case: truelogging:level:org:star:mapper: debug

2.5、主启动

/*** @Author : 一叶浮萍归大海* @Date: 2023/12/10 12:44* @Description:**/
@MapperScan(basePackages = "org.star.mapper")
@SpringBootApplication
public class SpringbootRedisDistributeCacheAnnotationApplication {public static void main(String[] args) {SpringApplication.run(SpringbootRedisDistributeCacheAnnotationApplication.class, args);}}

2.6、MyRedisConfig

/*** @Author : 一叶浮萍归大海* @Date: 2023/12/10 15:28* @Description:* @EnableCaching的作用:开启Spring的缓存,如果不加此注解的话Spring自带的缓存将不生效**/
@EnableCaching
@Configuration
public class MyRedisConfig {/*** RedisTemplate k v 序列化** @param connectionFactory* @return*/@Beanpublic RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);redisTemplate.setKeySerializer(RedisSerializer.string());redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashKeySerializer(RedisSerializer.string());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.afterPropertiesSet();return redisTemplate;}@Beanpublic RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()// 设置默认的超时时间为2小时.entryTtl(Duration.ofHours(2)).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()))// 设置默认的缓存前缀.prefixCacheNameWith("REDIS_CACHE_");return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);}}

2.7、DepartmentDO

/*** @Author : 一叶浮萍归大海* @Date: 2023/12/10 12:48* @Description:*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@ToString(callSuper = true)
public class DepartmentDO implements Serializable {/*** 编号*/private Integer id;/*** 部门名称*/private String departmentName;}

2.8、DepartmentMapper.java

/*** @Author : 一叶浮萍归大海* @Date: 2023/12/10 12:50* @Description:*/
public interface DepartmentMapper {/*** 查询所有部门* @return*/List<DepartmentDO> listAllDepartment();/*** 根据id查询部门信息* @param id* @return*/DepartmentDO getDepartmentById(Integer id);/*** 根据id和departmentName查询部门* @param id* @param departmentName* @return*/DepartmentDO getDepartment(Integer id,String departmentName);/*** 更新Department* @param department* @return*/int updateDepartment(DepartmentDO department);/*** 删除部门* @param id*/void deleteDepartment(Integer id);
}

2.9、DepartmentMapper.xml

<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="org.star.mapper.DepartmentMapper"><select id="listAllDepartment" resultType="org.star.entity.model.DepartmentDO">select id,department_name from department</select><select id="getDepartmentById" resultType="org.star.entity.model.DepartmentDO">select id,department_name from department where id = #{id}</select><select id="getDepartment" resultType="org.star.entity.model.DepartmentDO">select id,department_name from department where id = #{id} and department_name = #{departmentName}</select><update id="updateDepartment" useGeneratedKeys="true" keyProperty="id">update department set department_name = #{departmentName} where id = #{id}<selectKey resultType="org.star.entity.model.DepartmentDO" order="AFTER" keyProperty="id">select id,department_name from department where id = #{id}</selectKey></update><delete id="deleteDepartment">delete from department where id = #{id}</delete></mapper>

2.10、DepartmentService

/*** @Author : 一叶浮萍归大海* @Date: 2023/12/10 20:00* @Description:* 基于注解的分布式缓存,redis中key的生成规则:${prefixCacheNameWith} + "_" + ${cacheNames} + "_" + ${key}*      说明:prefixCacheNameWith为RedisCacheManager中配置的前缀*      举例:*          (1)listAllDepartment ===> REDIS_CACHE_org.star.service.DepartmentService::SimpleKey []*          (2)getDepartmentById ===> REDIS_CACHE_org.star.service.DepartmentService::1*          (3)getDepartment ===> REDIS_CACHE_org.star.service.DepartmentService::SimpleKey [1,研发部]**/
@Service
@CacheConfig(cacheNames = "org.star.service.DepartmentService")
public class DepartmentService {@Resourceprivate DepartmentMapper departmentMapper;/*** @return* @Cacheable的作用:*      @Cacheable注解一般加在查询方法上,表示将一个方法的返回值缓存起来,* 默认情况下,缓存的key就是方法的参数,缓存的value就是方法的返回值,如果查询* 方法无参数,则会使用默认的key,即SimpleKey []*/@Cacheablepublic List<DepartmentDO> listAllDepartment() {List<DepartmentDO> departments = departmentMapper.listAllDepartment();return departments;}/*** 对于只有一个参数的查询方法,其key位id对应的值* @param id* @return*/@Cacheablepublic DepartmentDO getDepartmentById(Integer id) {return departmentMapper.getDepartmentById(id);}/**** 对于有多个参数的查询方法,其key为所有的参数,如果想修改,可以单独指定,例如:@Cacheable(key = "#id")* @param id* @param departmentName* @return*/@Cacheablepublic DepartmentDO getDepartment(Integer id,String departmentName) {return departmentMapper.getDepartment(id,departmentName);}/*** @CachePut作用:*      @CachePut注解一般加在更新方法上(update),当数据库中的数据更新后,缓存中的数据也要跟着更新,使用此注解,可以将方法的返回值*      自动更新到已经存在的key上,示例如下:* @param department* @return*/@CachePut(key = "#department.id")public DepartmentDO updateDepartment(DepartmentDO department) {departmentMapper.updateDepartment(department);return department;}/*** @CacheEvict()作用:*      @CacheEvict()注解一般加在删除方法上,当数据库中的数据删除后,相关的缓存也会被删除,使用该注解的时候,也可以配置按照某种条件*      删除(某种条件:@CacheEvict注解中的条件,例如:value、cacheNames、key、keyGenerator...)* @param id*/@CacheEvictpublic void deleteDepartment(Integer id) {departmentMapper.deleteDepartment(id);}}

2.11、DepartmentServiceTest

/*** @Author : 一叶浮萍归大海* @Date: 2023/12/10 20:07* @Description:*/
@SpringBootTest
public class DepartmentServiceTest {@Resourceprivate DepartmentService departmentService;@Testpublic void listAllDepartmentTest() {List<DepartmentDO> departments1 = departmentService.listAllDepartment();System.out.println("departments1 = " + departments1);System.out.println("=============================");List<DepartmentDO> departments2 = departmentService.listAllDepartment();System.out.println("departments2 = " + departments2);}@Testpublic void getDepartmentByIdTest() {DepartmentDO department1 = departmentService.getDepartmentById(1);System.out.println("department1 = " + department1);System.out.println("========================");DepartmentDO department2 = departmentService.getDepartmentById(1);System.out.println("department2 = " + department2);}@Testpublic void getDepartmentTest() {DepartmentDO department1 = departmentService.getDepartment(1, "研发部");System.out.println("department1 = " + department1);System.out.println("============================");DepartmentDO department2 = departmentService.getDepartment(1, "研发部");System.out.println("department2 = " + department2);}@Testpublic void updateDepartmentTest() {DepartmentDO department = new DepartmentDO().setDepartmentName("研发部444").setId(1);DepartmentDO updatedDepartment = departmentService.updateDepartment(department);System.out.println("updatedDepartment = " + updatedDepartment);}@Testpublic void deleteDepartmentTest() {departmentService.deleteDepartment(1);}}

2.12、测试

2.12.1、listAllDepartmentTest

2.12.2、 getDepartmentByIdTest

2.12.3、getDepartmentTest

2.12.4、 updateDepartmentTest

2.12.5、 deleteDepartmentTest

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/267937.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mysql:建议使用INT UNSIGNED类型存储IPv4地址

建议使用INT UNSIGNED类型存储IPv4地址&#xff0c;而不要使用INT类型&#xff0c;也不建议使用VARCHAR(15)类型存储。 在mysql中&#xff0c;内嵌函数INET_ATON(expr)可以将IP地址字符串转换为整数&#xff0c;内嵌函数INET_NTOA(expr)可以将整数转换为ip地址字符串。 例如&a…

使用Kali Linux端口扫描

端口扫描 【实训目的】 掌握端口扫描的基本概念和端口扫描的原理&#xff0c;掌握各种类型端口扫描的方法及其区别。 【场景描述】 在虚拟机环境下配置4个虚拟系统“Win XP1” “Win XP2” “Kali Linux”和“Metasploitable2”&#xff0c;使得4个系统之间能够相互通信。实…

.net6 打包成exe文件启动后,只能localhost访问,无法使用ip访问

背景&#xff1a; 公司其他部门采用了.net6开发了一个小服务&#xff0c;需要我这边部署到winserver上&#xff0c;由于之前没有了解过.net6,就直接进行部署了&#xff0c;发现点击exe直接启动了&#xff0c;也没报错&#xff0c;在服务器上也可以通过localhost进行访问&#…

六级翻译之印章

好像大房子挺难得 三段式 1Since ancient from now&#xff0c;seals have been a symbol of power and certerfiction of identity.seals not only practical but also is a form of art.Seal is an ancient art combining with manafutuer of crafting and desgin of…

arkts编译报错-arkts-limited-stdlib错误【Bug已完美解决-鸿蒙开发】

文章目录 项目场景:问题描述原因分析:解决方案:适配指导案例此Bug解决方案总结项目场景: arkts编译报错-arkts-limited-stdlib错误。 我用Deveco studio4.0 beta2开发应用,报arkts-limited-stdlib错误 报错内容为: ERROR: ArKTS:ERROR File: D:/prRevivw/3792lapplica…

胡桃工具箱 原神多功能工具箱

胡桃工具箱 原神胡桃工具箱是一款非常实用的游戏工具辅助软件&#xff0c;可以为用户们提供优质的原神游戏工具&#xff0c;体验更精彩的游戏辅助&#xff0c;提供帧率解锁游戏功能&#xff0c;包括数据查询、游戏详解以及各种实用的功能。 安装使用 1.获取胡桃工具箱 请点击…

EasyExcel处理表头的缓存设置

在学习EasyExcel 时会发现针对使用类模型配置表头相关属性时&#xff0c;EasyExcel 会使用到缓存技术以提升表头的解析速度如下代码&#xff1a; 这些参数再何时设置的哪&#xff1f; 在easyExcel 基础参数设置中会有这个参数filedCacheLocation 。默认采用的使用线程级别的…

华为或荣耀手机禁止强制升级鸿蒙系统的终极方法

需要有数据传输的usb线.打开usb调试模式. 进这个链接下载华为ADB一键卸载VS重装软件 按里面的视频说明,输入88 然后回车即可 https://download.csdn.net/download/viqecel/12161462

【神行百里】pandas查询加速之行索引篇

最近进行大数据处理的时候&#xff0c;发现我以前常用的pandas查询方法太慢了&#xff0c;太慢了&#xff0c;真是太慢了&#xff0c;查阅资料&#xff0c;遂发现了一种新的加速方法&#xff0c;能助力我飞上天&#xff0c;和太阳肩并肩&#xff0c;所以记录下来。 1. 场景说明…

HyperGCN代码复现

环境&#xff1a;python3.6.7&#xff0c;torch0.4&#xff0c;外加pyyaml。 问题1:TypeError: cant convert np.ndarray of type numpy.intc. The only supported types are: double, float, float16, int64, int32, and uint8. 解决办法&#xff1a; 复现结果&#xff1a; …

weblogic部署应用包(从开发到部署)

想了解下weblogic部署流程&#xff0c;由于电脑没有应用程序&#xff0c;所以自己搞个test.war应用程序测试 软件 1-软件&#xff1a;jdk版本 2-path变量值增加&#xff1a;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPow…

力扣每日一题:2454. 下一个更大元素 IV(2023-12-12)

力扣每日一题&#xff08;今天的困难题&#xff0c;没有想到太好的方法&#xff0c;执行用时太久了&#xff09; 题目&#xff1a;2454. 下一个更大元素 IV 日期&#xff1a;2023-12-12 用时&#xff1a;35 m 09 s 时间&#xff1a;614ms 内存&#xff1a;57.18MB 代码&#x…