為什麼多級緩存
緩存的引入是現在大部分系統所必須考慮的
- redis 作為常用中間件,雖然我們一般業務系統(畢竟業務量有限)不會遇到如下圖 在隨著 data-size 的增大和數據結構的複雜的造成性能下降,但網絡 IO 消耗會成為整個調用鏈路中不可忽視的部分。尤其在 微服務架構中,一次調用往往會涉及多次調用 例如pig oauth2.0 的 client 認證
- Caffeine 來自未來的本地內存緩存,性能比如常見的內存緩存實現性能高出不少詳細對比。
綜合所述:我們需要構建 L1 Caffeine JVM 級別緩存 , L2 Redis 緩存。
設計難點
目前大部分應用緩存都是基於 Spring Cache 實現,基於註解(annotation)的緩存(cache)技術,存在的問題如下:
- Spring Cache 僅支持 單一的緩存來源,即:只能選擇 Redis 實現或者 Caffeine 實現,並不能同時使用。
- 數據一致性:各層緩存之間的數據一致性問題,如應用層緩存和分佈式緩存之前的數據一致性問題。
- 緩存過期:Spring Cache 不支持主動的過期策略
業務流程
如何使用
-
- 引入依賴
<dependency>
<groupId>com.pig4cloud.plugin</groupId>
<artifactId>multilevel-cache-spring-boot-starter</artifactId>
<version>0.0.1</version>
</dependency>
-
- 開啟緩存支持
@EnableCaching
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
-
- 目標接口聲明 Spring Cache 註解
@Cacheable(value = "get",key = "#key")
@GetMapping("/get")
public String get(String key){
return "success";
}
性能比較
為保證性能 redis 在 127.0.0.1 環路安裝
- OS: macOS Mojave
- CPU: 2.3 GHz Intel Core i5
- RAM: 8 GB 2133 MHz LPDDR3
- JVM: corretto_11.jdk
Benchmark | Mode | Cnt | Score | Units |
---|---|---|---|---|
多級實現 | thrpt | 2 | 2716.074 | ops/s |
默認 redis | thrpt | 2 | 1373.476 | ops/s |
代碼原理
-
- 自定義 CacheManager 多級緩存實現
public class RedisCaffeineCacheManager implements CacheManager {
@Override
public Cache getCache(String name) {
Cache cache = cacheMap.get(name);
if (cache != null) {
return cache;
}
cache = new RedisCaffeineCache(name, stringKeyRedisTemplate, caffeineCache(), cacheConfigProperties);
Cache oldCache = cacheMap.putIfAbsent(name, cache);
log.debug("create cache instance, the cache name is : {}", name);
return oldCache == null ? cache : oldCache;
}
}
-
- 多級讀取、過期策略實現
public class RedisCaffeineCache extends AbstractValueAdaptingCache {
protected Object lookup(Object key) {
Object cacheKey = getKey(key);
// 1. 先調用 caffeine 查詢是否存在指定的值
Object value = caffeineCache.getIfPresent(key);
if (value != null) {
log.debug("get cache from caffeine, the key is : {}", cacheKey);
return value;
}
// 2. 調用 redis 查詢在指定的值
value = stringKeyRedisTemplate.opsForValue().get(cacheKey);
if (value != null) {
log.debug("get cache from redis and put in caffeine, the key is : {}", cacheKey);
caffeineCache.put(key, value);
}
return value;
}
}
-
- 過期策略,所有更新操作都基於 redis pub/sub 消息機制更新
public class RedisCaffeineCache extends AbstractValueAdaptingCache {
@Override
public void put(Object key, Object value) {
push(new CacheMessage(this.name, key));
}
@Override
public ValueWrapper putIfAbsent(Object key, Object value) {
push(new CacheMessage(this.name, key));
}
@Override
public void evict(Object key) {
push(new CacheMessage(this.name, key));
}
@Override
public void clear() {
push(new CacheMessage(this.name, null));
}
private void push(CacheMessage message) {
stringKeyRedisTemplate.convertAndSend(topic, message);
}
}
-
- MessageListener 刪除指定 Caffeine 的指定值
public class CacheMessageListener implements MessageListener {
private final RedisTemplate<Object, Object> redisTemplate;
private final RedisCaffeineCacheManager redisCaffeineCacheManager;
@Override
public void onMessage(Message message, byte[] pattern) {
CacheMessage cacheMessage = (CacheMessage) redisTemplate.getValueSerializer().deserialize(message.getBody());
cacheMessage.getCacheName(), cacheMessage.getKey());
redisCaffeineCacheManager.clearLocal(cacheMessage.getCacheName(), cacheMessage.getKey());
}
}
源碼地址
[https://github.com/pig-mesh/multilevel-cache-spring-boot-starter
](https://github.com/pig-mesh/multilevel-cache-spring-boot-starter)