java如何缓存
缓存实现方法
在Java中实现缓存可以通过多种方式,包括使用内置集合、第三方库或框架。以下是几种常见的方法:
使用HashMap实现简单缓存
创建一个基于HashMap的缓存类,设置过期时间和最大容量限制。需要手动处理并发和过期清理。
public class SimpleCache<K, V> {
private final Map<K, V> cache = new HashMap<>();
private final long expireTime;
public SimpleCache(long expireTime) {
this.expireTime = expireTime;
}
public synchronized void put(K key, V value) {
cache.put(key, value);
}
public synchronized V get(K key) {
return cache.get(key);
}
}
使用Guava Cache
Google Guava库提供了强大的缓存实现,支持自动加载、过期策略和大小限制。
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
cache.put("key", "value");
String value = cache.getIfPresent("key");
使用Caffeine
Caffeine是高性能Java缓存库,比Guava Cache更高效。
Cache<String, String> cache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.maximumSize(100)
.build();
cache.put("key", "value");
String value = cache.getIfPresent("key");
使用Spring Cache
Spring框架提供了声明式缓存抽象,支持多种缓存实现。
@Cacheable(value = "users", key = "#userId")
public User getUser(String userId) {
return userRepository.findById(userId);
}
@CacheEvict(value = "users", key = "#userId")
public void updateUser(User user) {
userRepository.save(user);
}
缓存策略选择
LRU(最近最少使用) 适合大多数场景,优先移除最久未使用的数据。
LFU(最不经常使用) 根据使用频率淘汰数据,适合访问模式不均匀的场景。
FIFO(先进先出) 简单实现但可能淘汰热点数据。
TTL(生存时间) 设置固定过期时间,适合时效性强的数据。
分布式缓存方案
Redis 高性能内存数据库,支持丰富的数据结构和持久化。
Jedis jedis = new Jedis("localhost");
jedis.set("key", "value");
String value = jedis.get("key");
Memcached 简单高效的分布式内存缓存系统。
MemcachedClient client = new MemcachedClient(
new InetSocketAddress("localhost", 11211));
client.set("key", 3600, "value");
Object value = client.get("key");
缓存注意事项
缓存穿透 查询不存在的数据导致请求直达数据库。解决方案:布隆过滤器或缓存空值。
缓存雪崩 大量缓存同时失效导致数据库压力激增。解决方案:设置不同过期时间或实现高可用。
缓存一致性 确保缓存与数据库数据同步。解决方案:双写模式或失效模式。

监控指标 需要监控缓存命中率、响应时间、内存使用等关键指标。






