使用 Caffeine 和 Redis 實(shí)現(xiàn)高效的二級(jí)緩存架構(gòu)
在現(xiàn)代應(yīng)用開(kāi)發(fā)中,緩存是提升系統(tǒng)性能的關(guān)鍵手段。為了兼顧本地緩存的高性能和分布式緩存的擴(kuò)展能力,常見(jiàn)的實(shí)現(xiàn)方式是結(jié)合使用 Caffeine 和 Redis 實(shí)現(xiàn)二級(jí)緩存架構(gòu)。
本文將詳細(xì)介紹如何通過(guò) Spring Boot 實(shí)現(xiàn)一個(gè)Caffeine + Redis 二級(jí)緩存,并通過(guò)合理的架構(gòu)設(shè)計(jì)和代碼實(shí)現(xiàn),確保緩存的一致性、性能和容錯(cuò)性。
一、 需求與挑戰(zhàn)
1.多級(jí)緩存的需求:
- 一級(jí)緩存(Caffeine):快速響應(yīng),存儲(chǔ)本地?zé)狳c(diǎn)數(shù)據(jù),減少對(duì)遠(yuǎn)程緩存和數(shù)據(jù)庫(kù)的訪問(wèn)。
- 二級(jí)緩存(Redis):共享緩存數(shù)據(jù),支持分布式擴(kuò)展。
2.常見(jiàn)問(wèn)題:
- 數(shù)據(jù)一致性:一級(jí)緩存和二級(jí)緩存之間的數(shù)據(jù)如何保持同步?
- 容錯(cuò)性:Redis 不可用時(shí)如何保證系統(tǒng)穩(wěn)定運(yùn)行?
- 緩存穿透:如何避免大量無(wú)效請(qǐng)求穿透緩存直接訪問(wèn)數(shù)據(jù)庫(kù)?
- 高并發(fā):如何避免緩存擊穿導(dǎo)致數(shù)據(jù)庫(kù)壓力激增?
二、 緩存設(shè)計(jì)與解決方案
2.1 緩存查詢流程
按照Cache-Aside 模式,緩存查詢流程如下:
1.查詢一級(jí)緩存(Caffeine):
如果命中,則直接返回結(jié)果。
2.查詢二級(jí)緩存(Redis):
- 如果 Redis 有數(shù)據(jù),則回填到一級(jí)緩存,并返回結(jié)果。
- 如果 Redis 查詢失敗(Redis 不可用),直接跳過(guò)。
3.查詢數(shù)據(jù)源(數(shù)據(jù)庫(kù)等):
如果 Redis 也未命中,則從數(shù)據(jù)源獲取數(shù)據(jù),同時(shí)回填到一級(jí)和二級(jí)緩存中。
2.2 緩存更新流程
- 數(shù)據(jù)更新或?qū)懭霑r(shí),同時(shí)更新一級(jí)和二級(jí)緩存。
- 如果 Redis 寫(xiě)入失敗,僅更新一級(jí)緩存,確保數(shù)據(jù)可用性。
三、代碼實(shí)現(xiàn)
3.1 緩存接口設(shè)計(jì)
定義一個(gè)通用的緩存接口,便于不同實(shí)現(xiàn)類的擴(kuò)展和切換:
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
public interface CacheService {
<T> T get(String key, Class<T> type, Supplier<T> dataLoader); // 獲取單個(gè)鍵的數(shù)據(jù)
void put(String key, Object value); // 存儲(chǔ)單個(gè)鍵的數(shù)據(jù)
void evict(String key); // 刪除單個(gè)鍵
boolean exists(String key); // 檢查鍵是否存在
Map<String, Object> getAll(Set<String> keys); // 批量獲取多個(gè)鍵的數(shù)據(jù)
Object getHash(String key, String hashKey); // 獲取哈希表中單個(gè)字段的值
void putHash(String key, String hashKey, Object value); // 存儲(chǔ)哈希表中的字段
void evictAll(Collection<String> keys); // 批量刪除多個(gè)鍵
}
3.2 Caffeine + Redis 實(shí)現(xiàn)
使用 Caffeine 和 Redis 的結(jié)合實(shí)現(xiàn)二級(jí)緩存:
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
@Service
public class OptimizedCacheService implements CacheService {
private final Cache<String, Object> caffeineCache;
private final RedisTemplate<String, Object> redisTemplate;
public OptimizedCacheService(RedisTemplate<String, Object> redisTemplate) {
this.caffeineCache = Caffeine.newBuilder()
.initialCapacity(100)
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
this.redisTemplate = redisTemplate;
}
@Override
public <T> T get(String key, Class<T> type, Supplier<T> dataLoader) {
// Step 1: 查詢一級(jí)緩存(Caffeine)
T value = (T) caffeineCache.getIfPresent(key);
if (value != null) {
return value;
}
// Step 2: 查詢二級(jí)緩存(Redis)
try {
value = (T) redisTemplate.opsForValue().get(key);
if (value != null) {
// 回填到一級(jí)緩存
caffeineCache.put(key, value);
return value;
}
} catch (Exception e) {
// Redis 不可用時(shí)記錄日志
System.err.println("Redis 不可用:" + e.getMessage());
}
// Step 3: 查詢數(shù)據(jù)源(數(shù)據(jù)庫(kù)等)
value = dataLoader.get();
if (value != null) {
// 回填到緩存
caffeineCache.put(key, value);
try {
redisTemplate.opsForValue().set(key, value, 10, TimeUnit.MINUTES);
} catch (Exception e) {
System.err.println("Redis 存儲(chǔ)失?。? + e.getMessage());
}
}
return value;
}
@Override
public void put(String key, Object value) {
// 同時(shí)更新一級(jí)緩存和二級(jí)緩存
caffeineCache.put(key, value);
try {
redisTemplate.opsForValue().set(key, value, 10, TimeUnit.MINUTES);
} catch (Exception e) {
System.err.println("Redis 存儲(chǔ)失?。? + e.getMessage());
}
}
@Override
public void evict(String key) {
// 同時(shí)移除一級(jí)緩存和二級(jí)緩存
caffeineCache.invalidate(key);
try {
redisTemplate.delete(key);
} catch (Exception e) {
System.err.println("Redis 刪除失?。? + e.getMessage());
}
}
@Override
public boolean exists(String key) {
// 檢查一級(jí)緩存
if (caffeineCache.asMap().containsKey(key)) {
return true;
}
// 檢查二級(jí)緩存
try {
return Boolean.TRUE.equals(redisTemplate.hasKey(key));
} catch (Exception e) {
System.err.println("Redis 檢查鍵失敗:" + e.getMessage());
return false;
}
}
@Override
public Map<String, Object> getAll(Set<String> keys) {
// 優(yōu)先從一級(jí)緩存中獲取
Map<String, Object> result = caffeineCache.getAllPresent(keys);
// 還需要獲取的鍵
Set<String> missingKeys = keys.stream()
.filter(key -> !result.containsKey(key))
.collect(Collectors.toSet());
if (!missingKeys.isEmpty()) {
try {
// 從 Redis 獲取剩余的鍵
List<Object> redisResults = redisTemplate.opsForValue().multiGet(missingKeys);
if (redisResults != null) {
for (int i = 0; i < missingKeys.size(); i++) {
String key = missingKeys.toArray(new String[0])[i];
Object value = redisResults.get(i);
if (value != null) {
result.put(key, value);
caffeineCache.put(key, value); // 回填一級(jí)緩存
}
}
}
} catch (Exception e) {
System.err.println("Redis 批量獲取失?。? + e.getMessage());
}
}
return result;
}
@Override
public Object getHash(String key, String hashKey) {
try {
return redisTemplate.opsForHash().get(key, hashKey);
} catch (Exception e) {
System.err.println("Redis 獲取哈希字段失敗:" + e.getMessage());
return null;
}
}
@Override
public void putHash(String key, String hashKey, Object value) {
try {
redisTemplate.opsForHash().put(key, hashKey, value);
} catch (Exception e) {
System.err.println("Redis 存儲(chǔ)哈希字段失?。? + e.getMessage());
}
}
@Override
public void evictAll(Collection<String> keys) {
// 刪除一級(jí)緩存
caffeineCache.invalidateAll(keys);
// 刪除二級(jí)緩存
try {
redisTemplate.delete(keys);
} catch (Exception e) {
System.err.println("Redis 批量刪除失敗:" + e.getMessage());
}
}
}
3.3 空值緩存(防止緩存穿透)
為了避免查詢不存在的數(shù)據(jù)穿透到數(shù)據(jù)庫(kù),可以將空值存儲(chǔ)到緩存中:
if (value == null) {
// 存儲(chǔ)空值到緩存,防止穿透
caffeineCache.put(key, "NULL");
try {
redisTemplate.opsForValue().set(key, "NULL", 1, TimeUnit.MINUTES);
} catch (Exception e) {
System.err.println("Redis 存儲(chǔ)空值失?。? + e.getMessage());
}
return null;
}
if ("NULL".equals(value)) {
return null;
}
3.4 異步更新 Redis(提升寫(xiě)性能)
為了提高寫(xiě)操作性能,可以將 Redis 的更新操作放到異步線程中:
private void asyncUpdateRedis(String key, Object value) {
new Thread(() -> {
try {
redisTemplate.opsForValue().set(key, value, 10, TimeUnit.MINUTES);
} catch (Exception e) {
System.err.println("Redis 異步更新失?。? + e.getMessage());
}
}).start();
}
在put和get方法中調(diào)用asyncUpdateRedis。
3.5 定時(shí)清理 Caffeine
Caffeine 默認(rèn)是惰性清理(Lazy Cleanup)。如果需要主動(dòng)清理,可以通過(guò)定時(shí)任務(wù)觸發(fā):
@Scheduled(fixedRate = 60000) // 每分鐘執(zhí)行一次
public void cleanUpCache() {
caffeineCache.cleanUp();
}
四、總結(jié)與優(yōu)勢(shì)
4.1 架構(gòu)特點(diǎn)
- 性能更高:直接按一級(jí)緩存 -> 二級(jí)緩存 -> 數(shù)據(jù)庫(kù)的順序查詢,減少了 Redis 可用性檢查的開(kāi)銷。
- 降級(jí)容錯(cuò):當(dāng) Redis 不可用時(shí),不影響數(shù)據(jù)加載和緩存更新。
- 緩存一致性:通過(guò)回填機(jī)制,盡量保持一級(jí)緩存和二級(jí)緩存的數(shù)據(jù)一致性。
- 可擴(kuò)展性:支持空值緩存、異步更新、主動(dòng)清理等增強(qiáng)功能。
4.2 應(yīng)用場(chǎng)景
- 高頻訪問(wèn)的數(shù)據(jù)(如熱門商品、熱點(diǎn)新聞)。
- 分布式應(yīng)用需要共享緩存的數(shù)據(jù)。
- 對(duì)性能和容錯(cuò)性有較高要求的業(yè)務(wù)場(chǎng)景。
通過(guò) Caffeine 和 Redis 的結(jié)合,可以構(gòu)建一個(gè)高效、靈活、穩(wěn)定的二級(jí)緩存架構(gòu),有效提升系統(tǒng)性能并降低后端服務(wù)壓力。