java内存缓存实现 与 redis缓存实现 (ConcurrentHashMap 应用)
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;@Service
public class LocalCacheService {// 核心内存缓存容器(线程安全的ConcurrentHashMap)private final Map<String, Object> localCache = new ConcurrentHashMap<>();/*** 通用内存缓存获取方法* @param cacheKey 缓存键* @param dataLoader 数据加载器(缓存未命中时执行)* @return 缓存或加载的数据*/public <T> T getFromLocalCache(String cacheKey, Supplier<T> dataLoader) {// 1. 从内存缓存获取数据@SuppressWarnings("unchecked")T data = (T) localCache.get(cacheKey);// 2. 缓存命中,直接返回if (data != null) {return data;}// 3. 缓存未命中,执行数据加载逻辑data = dataLoader.get();// 4. 加载成功后放入内存缓存if (data != null) {localCache.put(cacheKey, data);}return data;}/*** 主动清除指定缓存* @param cacheKey 缓存键*/public void removeLocalCache(String cacheKey) {localCache.remove(cacheKey);}/*** 清空所有内存缓存(谨慎使用)*/public void clearAllLocalCache() {localCache.clear();}
}
上面的是 内存缓存
下面的是 redis缓存
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import java.util.function.Supplier;@Service
public class CacheService {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;/*** 通用缓存获取方法* @param cacheKey 缓存键* @param dataLoader 数据加载器函数* @return 缓存或数据库中的数据*/public <T> T getFromCache(String cacheKey, Supplier<T> dataLoader) {// 从缓存获取数据T data = (T) redisTemplate.opsForValue().get(cacheKey);if (data != null) {return data;}// 缓存未命中,加载数据data = dataLoader.get();if (data != null) {// 放入缓存(永不过期)redisTemplate.opsForValue().set(cacheKey, data);}return data;}
}
本文展示了两种缓存实现方案:1) 基于ConcurrentHashMap的本地内存缓存(LocalCacheService),提供线程安全的缓存操作,包含缓存查询、自动加载、单键清除和全部清除功能;2) Redis分布式缓存(CacheService),通过RedisTemplate实现,包含基本的缓存查询和自动加载功能。两种方案均采用Supplier接口实现"缓存未命中时自动加载"的模式,其中本地缓存适用于单机高频访问场景,Redis缓存适用于分布式环境。代码结构清晰,展示了Sprin