java如何使用缓存
Java 缓存的使用方法
Java 中缓存的使用可以通过多种方式实现,包括使用内置的缓存机制、第三方库或框架。以下是几种常见的缓存使用方法:
使用 HashMap 实现简单缓存
创建一个基于 HashMap 的简单缓存,适合小规模数据缓存需求。
import java.util.HashMap;
import java.util.Map;
public class SimpleCache<K, V> {
private final Map<K, V> cache = new HashMap<>();
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);
}
public void clear() {
cache.clear();
}
}
使用 Caffeine 缓存库
Caffeine 是一个高性能的 Java 缓存库,支持多种缓存策略。
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);
}
}
使用 Guava Cache
Guava Cache 是 Google 提供的一个缓存库,功能丰富且易于使用。
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
public class GuavaCacheExample {
public static void main(String[] args) {
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
return "default-value";
}
});
cache.put("key1", "value1");
String value = cache.getIfPresent("key1");
System.out.println(value);
}
}
使用 Ehcache
Ehcache 是一个广泛使用的开源 Java 缓存框架,支持分布式缓存。
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
public class EhcacheExample {
public static void main(String[] args) {
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("preConfigured",
CacheConfigurationBuilder.newCacheConfigurationBuilder(
String.class, String.class,
ResourcePoolsBuilder.heap(100)))
.build();
cacheManager.init();
Cache<String, String> cache = cacheManager.getCache("preConfigured", String.class, String.class);
cache.put("key1", "value1");
String value = cache.get("key1");
System.out.println(value);
cacheManager.close();
}
}
使用 Spring Cache 注解
在 Spring 框架中,可以通过注解轻松实现缓存功能。
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class BookService {
@Cacheable("books")
public String getBook(String isbn) {
// Simulate slow operation
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Book-" + isbn;
}
}
缓存的最佳实践
- 设置合适的缓存大小:根据应用需求调整缓存的最大容量,避免内存溢出。
- 选择合适的缓存策略:如 LRU(最近最少使用)、LFU(最不经常使用)等。
- 处理缓存穿透:对于不存在的键,避免频繁查询数据库。
- 处理缓存雪崩:设置不同的过期时间,避免大量缓存同时失效。
- 监控缓存命中率:定期检查缓存命中率,优化缓存策略。
以上方法涵盖了从简单到复杂的缓存实现,可以根据具体需求选择合适的方案。







