SpringBoot中怎麼透過自訂快取註解實現資料庫資料快取到Redis
實作
首先在Mysql中新建一個表格bus_student
#然後基於此表使用程式碼生成,前端Vue與後台各層程式碼生成並新增選單。
然後來到後台程式碼中,在後台框架中已經加入了操作redis的相關依賴和工具類別。
但這裡還需要加入aspect依賴
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --><dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.14.RELEASE</version> </dependency>
然後在存放配置類別的地方新建新增redis快取的註解
package com.ruoyi.system.redisAop; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;/* * @Author * @Description 新增redis缓存 **/@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)public @interface AopCacheEnable {//redis缓存key String[] key();//redis缓存存活时间默认值(可自定义)long expireTime() default 3600; }
以及刪除redis快取的註解
#package com.ruoyi.system.redisAop; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;/* * @Description 删除redis缓存注解 **/@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME)public @interface AopCacheEvict {//redis中的key值 String[] key(); }
接著再新建一個自訂快取切面具體實作類別CacheEnableAspect
。存放位置
package com.ruoyi.system.redisAop; import com.ruoyi.system.domain.BusStudent; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit;/* * @Description 自定义缓存切面具体实现类 **/@Aspect @Componentpublic class CacheEnableAspect { @Autowiredpublic RedisTemplate redisCache;/** * Mapper层切点 使用到了我们定义的 AopCacheEnable 作为切点表达式。 */@Pointcut("@annotation(com.ruoyi.system.redisAop.AopCacheEnable)")public void queryCache() { }/** * Mapper层切点 使用到了我们定义的 AopCacheEvict 作为切点表达式。 */@Pointcut("@annotation(com.ruoyi.system.redisAop.AopCacheEvict)")public void ClearCache() { } @Around("queryCache()")public Object Interceptor(ProceedingJoinPoint pjp) { Object result = null;//注解中是否有#标识boolean spelFlg = false;//判断是否需要走数据库查询boolean selectDb = false;//redis中缓存的keyString redisKey = "";//获取当前被切注解的方法名Method method = getMethod(pjp);//获取当前被切方法的注解AopCacheEnable aopCacheEnable = method.getAnnotation(AopCacheEnable.class);//获取方法参数值Object[] arguments = pjp.getArgs();//从注解中获取字符串String[] spels = aopCacheEnable.key();for (String spe1l : spels) {if (spe1l.contains("#")) {//注解中包含#标识,则需要拼接spel字符串,返回redis的存储redisKeyredisKey = spe1l.substring(1) + arguments[0].toString(); } else {//没有参数或者参数是List的方法,在缓存中的keyredisKey = spe1l; }//取出缓存中的数据result = redisCache.opsForValue().get(redisKey);//缓存是空的,则需要重新查询数据库if (result == null || selectDb) {try { result = pjp.proceed();//从数据库查询到的结果不是空的if (result != null && result instanceof ArrayList) {//将redis中缓存的结果转换成对象listList<BusStudent> students = (List<BusStudent>) result;//判断方法里面的参数是不是BusStudentif (arguments[0] instanceof BusStudent) {//将rediskey-students 存入到redisredisCache.opsForValue().set(redisKey, students, aopCacheEnable.expireTime(), TimeUnit.SECONDS); } } } catch (Throwable e) { e.printStackTrace(); } } }return result; }/*** 定义清除缓存逻辑,先操作数据库,后清除缓存*/@Around(value = "ClearCache()")public Object evict(ProceedingJoinPoint pjp) throws Throwable {//redis中缓存的keyMethod method = getMethod(pjp);// 获取方法的注解AopCacheEvict cacheEvict = method.getAnnotation(AopCacheEvict.class);//先操作dbObject result = pjp.proceed();// 获取注解的key值String[] fieldKeys = cacheEvict.key();for (String spe1l : fieldKeys) {//根据key从缓存中删除 redisCache.delete(spe1l); }return result; }/** * 获取被拦截方法对象 */public Method getMethod(ProceedingJoinPoint pjp) { Signature signature = pjp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method targetMethod = methodSignature.getMethod();return targetMethod; } }
注意這裡的queryCache和ClearCache,內切點表達式
分別對應上面自訂的兩個AopCacheEnable和AopCacheEvict。
然後在環繞通知的queryCache方法執行前後時
取得被切方法的參數,參數中的key,然後根據key去redis中去查詢,
如果查不到,就把方法的回傳結果轉換成物件List,存入redis中,
如果能查到,則將結果傳回。
然後找到這個表的查詢方法,mapper層,例如要將查詢的回傳結果儲存進redis
@AopCacheEnable(key = "BusStudent",expireTime = 40)public List<BusStudent> selectBusStudentList(BusStudent busStudent);
然後在這個表的新增、編輯、刪除的mapper方法上添加
/** * 新增学生 * * @param busStudent 学生 * @return 结果 */@AopCacheEvict(key = "BusStudent")public int insertBusStudent(BusStudent busStudent);/** * 修改学生 * * @param busStudent 学生 * @return 结果 */@AopCacheEvict(key = "BusStudent")public int updateBusStudent(BusStudent busStudent);/** * 删除学生 * * @param id 学生ID * @return 结果 */@AopCacheEvict(key = "BusStudent")public int deleteBusStudentById(Integer id);
注意這裡的註解上的key要和上面的查詢的註解的key一致。
然後啟動項目,如果啟動時提示:
Consider marking one of the beans as @Primary, updating
the consumer to acce
#因為sringboot透過@Autowired注入介面的實作類別時發現有多個,也就是有多個類別繼承了這個接口,spring容器不知道使用哪一個。
找到redis的設定類,在RedisTemplate上新增@Primary註解
驗證註解的使用
debug啟動項目,在CacheEnableAspect中查詢註解中打斷點,然後呼叫查詢方法,
就可以看到能進斷點,然後就可以根據自己想要的邏輯和效果進行修改註解。
以上是SpringBoot中怎麼透過自訂快取註解實現資料庫資料快取到Redis的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

Redis集群模式通過分片將Redis實例部署到多個服務器,提高可擴展性和可用性。搭建步驟如下:創建奇數個Redis實例,端口不同;創建3個sentinel實例,監控Redis實例並進行故障轉移;配置sentinel配置文件,添加監控Redis實例信息和故障轉移設置;配置Redis實例配置文件,啟用集群模式並指定集群信息文件路徑;創建nodes.conf文件,包含各Redis實例的信息;啟動集群,執行create命令創建集群並指定副本數量;登錄集群執行CLUSTER INFO命令驗證集群狀態;使

使用 Redis 指令需要以下步驟:打開 Redis 客戶端。輸入指令(動詞 鍵 值)。提供所需參數(因指令而異)。按 Enter 執行指令。 Redis 返迴響應,指示操作結果(通常為 OK 或 -ERR)。

啟動 Redis 服務器的步驟包括:根據操作系統安裝 Redis。通過 redis-server(Linux/macOS)或 redis-server.exe(Windows)啟動 Redis 服務。使用 redis-cli ping(Linux/macOS)或 redis-cli.exe ping(Windows)命令檢查服務狀態。使用 Redis 客戶端,如 redis-cli、Python 或 Node.js,訪問服務器。

Redis 使用哈希表存儲數據,支持字符串、列表、哈希表、集合和有序集合等數據結構。 Redis 通過快照 (RDB) 和追加只寫 (AOF) 機制持久化數據。 Redis 使用主從復制來提高數據可用性。 Redis 使用單線程事件循環處理連接和命令,保證數據原子性和一致性。 Redis 為鍵設置過期時間,並使用 lazy 刪除機制刪除過期鍵。

使用Redis進行鎖操作需要通過SETNX命令獲取鎖,然後使用EXPIRE命令設置過期時間。具體步驟為:(1) 使用SETNX命令嘗試設置一個鍵值對;(2) 使用EXPIRE命令為鎖設置過期時間;(3) 當不再需要鎖時,使用DEL命令刪除該鎖。

要從 Redis 讀取隊列,需要獲取隊列名稱、使用 LPOP 命令讀取元素,並處理空隊列。具體步驟如下:獲取隊列名稱:以 "queue:" 前綴命名,如 "queue:my-queue"。使用 LPOP 命令:從隊列頭部彈出元素並返回其值,如 LPOP queue:my-queue。處理空隊列:如果隊列為空,LPOP 返回 nil,可先檢查隊列是否存在再讀取元素。

解決redis-server找不到問題的步驟:檢查安裝,確保已正確安裝Redis;設置環境變量REDIS_HOST和REDIS_PORT;啟動Redis服務器redis-server;檢查服務器是否運行redis-cli ping。

要查看 Redis 中的所有鍵,共有三種方法:使用 KEYS 命令返回所有匹配指定模式的鍵;使用 SCAN 命令迭代鍵並返回一組鍵;使用 INFO 命令獲取鍵的總數。
