AutoLoadCache 使用以及規範

簡介

AutoLoadCache 是基於AOP+Annotation等技術實現的高效的緩存管理解決方案,實現緩存與業務邏輯的解耦,並增加異步刷新及“拿來主義機制”,以適應高併發環境下的使用。
使用AOP + Annotation 來解決這個問題,同時使用自動加載機制 來實現數據“常駐內存”

—> 跳轉官方git

如何使用

本文的自動緩存使用的redis作爲緩存技術, 請確保自己系統中的redis能夠正常使用

引入jar包

<!-- autoload-cache 依賴 -->
<dependency>
    <groupId>com.github.qiujiayu</groupId>
    <artifactId>autoload-cache-spring-boot-starter</artifactId>
    <version>7.0.8</version>
</dependency>
<!-- aop 依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

配置類

package com.xxx

import com.jarvis.cache.ICacheManager;
import com.jarvis.cache.autoconfigure.AutoloadCacheProperties;
import com.jarvis.cache.clone.ICloner;
import com.jarvis.cache.map.MapCacheManager;
import com.jarvis.cache.serializer.FastjsonSerializer;
import com.jarvis.cache.serializer.ISerializer;
import org.springframework.context.annotation.Bean;

/**
 * @Author: WanG
 * @Date: 2020/6/9 10:32
 * @version: v1.0
 * @description: 自動緩存框架配置
 */
public class AutoloadCacheConfiguration {
	// @Bean
	public ICacheManager mapCacheManager(AutoloadCacheProperties config, ICloner cloner) {
		return new MapCacheManager(config.getConfig(), cloner);
	}

	@Bean
	public ISerializer<Object> autoloadCacheSerializer() {
		return new FastjsonSerializer();
	}
}

註解

Annotation: 官方例子

參數說明

  • #retVal 數組類型統一用這個取值, 或者用爲取返回值
  • #args 按座標取傳入參數
  • #hash 使用hash函數
  • #empty 使用empty判斷
  • expireExpression 過期時間表達式
  • condition 執行條件, 滿足改條件才生效(用於修改和刪除數據的時候連帶刪除緩存)
  • @ExCache 額外生成關聯緩存
  • @CacheDelete 刪除緩存註解
  • @CacheDeleteKey 生成刪除緩存Key註解
  • @CacheDeleteTransactional 事務環境中批量刪除緩存註解
  • @LocalCache 本地緩存註解

緩存數據

在需要進行數據緩存的地方加上@Cache註解即可

@Cache(expire = "{過期時間(這個是數字類型)}", key = "{緩存使用的key}")

清理緩存

在需要清理緩存的地方加上@CacheDelete 註解

 @CacheDelete({ @CacheDeleteKey(value = "{緩存使用的key}") })

動態過期時間

當返回值爲空時緩存有效期爲20分鐘, 當返回值不爲空有效期爲60分鐘

@Cache(expire = EXPIRE_TIME, key = CACHE_KEY_INITUSERINFO, expireExpression = "null == #retVal ? 20: 60")

動態

當刪除語句執行成功, 纔將對應key的緩存刪除

@CacheDelete({ @CacheDeleteKey(value = "'user-byid-' + #args[0]", condition = "#retVal > 0") })
int deleteUserById(Long id);

動態取值

註解裏面可以用#args[i]來動態獲取入參

    @Cache(expire = 60, expireExpression = "null == #retVal ? 30: 60", key = "'user-byid-' + #args[0]")
    UserDO getUserById(Long id);

使用規範

  1. 緩存key:作爲分隔符
  2. 緩存純數據庫字段key要加上table關鍵字
  3. 緩存方法數據key要加上method關鍵字
  4. 對數據進行修改或者刪除時務必同步將緩存刪除(帶上condition, 操作成功才動緩存)
  5. 方法緩存key中帶上類名和方法名(用.隔開)
  6. key中帶上緩存的入參, 並用=連接參數名和參數值
  7. 多個入參用,分隔

舉例

## 緩存key值:
user-server:method:+CacheServiceImpl.initUserInfo:personId=1,homeId=1

## 代碼樣例
public static final String CACHE_KEY_INITUSERINFO = CacheConfig.KEY_METHOD + "CacheServiceImpl.initUserInfo:personId='+#args[0]+',homeId='+#args[1]";
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章