java如何应用缓存
使用Java内置缓存
Java提供了简单的缓存机制,例如使用HashMap或ConcurrentHashMap实现缓存功能。这种方式适合小型应用或临时缓存需求。
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class SimpleCache<K, V> {
private final Map<K, V> cache = new ConcurrentHashMap<>();
public void put(K key, V value) {
cache.put(key, value);
}
public V get(K key) {
return cache.get(key);
}
public void remove(K key) {
cache.remove(key);
}
}
使用Guava Cache
Google的Guava库提供了功能丰富的缓存实现,支持过期策略、最大容量限制等特性。
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public class GuavaCacheExample {
public static void main(String[] args) {
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100)
.build();
cache.put("key1", "value1");
String value = cache.getIfPresent("key1");
System.out.println(value);
}
}
使用Caffeine
Caffeine是一个高性能的Java缓存库,比Guava Cache更高效,适合高并发场景。
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class CaffeineCacheExample {
public static void main(String[] args) {
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(100)
.build();
cache.put("key1", "value1");
String value = cache.getIfPresent("key1");
System.out.println(value);
}
}
使用Spring Cache
Spring框架提供了缓存抽象,支持多种缓存实现(如EhCache、Redis等),通过注解简化缓存操作。
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Cacheable("users")
public User getUserById(String id) {
// 模拟数据库查询
return new User(id, "User " + id);
}
}
使用Redis
Redis是一个分布式缓存解决方案,适合大规模应用。通过Jedis或Lettuce客户端与Redis交互。

import redis.clients.jedis.Jedis;
public class RedisCacheExample {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
jedis.set("key1", "value1");
String value = jedis.get("key1");
System.out.println(value);
jedis.close();
}
}
缓存策略选择
- LRU(最近最少使用):适合大多数场景,自动淘汰最久未使用的数据。
- TTL(生存时间):适合数据需要定期更新的场景。
- FIFO(先进先出):适合数据访问模式简单的场景。
缓存注意事项
- 缓存穿透:使用布隆过滤器或空值缓存避免频繁查询不存在的数据。
- 缓存雪崩:设置不同的过期时间或使用多级缓存。
- 数据一致性:通过双写或失效机制保证缓存与数据库的一致性。






