Java中的缓存:Redis、Memcached及内置解决方案:高级篇
缓存是提升Java应用程序性能和可扩展性的关键工具之一。在高级层面,开发者需要在分布式系统(Redis、Memcached)和轻量级内置缓存(Caffeine、Guava)之间做出选择。本文将分析它们的架构差异、应用场景,并为每种方案提供实用的代码示例。
1. 内置缓存:Caffeine 和 Guava
内置缓存在JVM内部运行,无需外部服务。它们非常适合存储无需在节点间同步的临时数据。
Caffeine —— 现代标准
Caffeine 是一个高性能的Java缓存库,它取代了 Guava Cache。它使用 Window TinyLFU 算法来高效地淘汰条目。
// Maven依赖// <dependency>// <groupId>com.github.ben-manes.caffeine</groupId>// <artifactId>caffeine</artifactId>// <version>3.1.8</version>// </dependency>
import com.github.benmanes.caffeine.cache.Cache;import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
public class CaffeineExample { public static void main(String[] args) { Cache<String, User> userCache = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(10_000) .recordStats() .build();
// 写入 userCache.put("user:123", new User("Alice", "alice@example.com"));
// 读取 User user = userCache.getIfPresent("user:123"); System.out.println("Cached user: " + user);
// 带加载的原子读取 User result = userCache.get("user:456", key -> loadUserFromDB(key)); }
private static User loadUserFromDB(String key) { // 模拟从数据库加载 return new User("Bob", "bob@example.com"); }
static class User { private final String name; private final String email;
User(String name, String email) { this.name = name; this.email = email; }
@Override public String toString() { return "User{name='" + name + "', email='" + email + "'}"; } }}Guava Cache —— 久经考验的解决方案
Google 的 Guava Cache 对于已使用 Guava 库的项目来说仍然是一个流行的选择。它支持多种淘汰策略和监听器。
import com.google.common.cache.CacheBuilder;import com.google.common.cache.CacheLoader;import com.google.common.cache.LoadingCache;
import java.util.concurrent.ExecutionException;import java.util.concurrent.TimeUnit;
public class GuavaCacheExample { public static void main(String[] args) throws ExecutionException { LoadingCache<String, String> cache = CacheBuilder.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) .maximumSize(5000) .removalListener(notification -> System.out.println("Removed: " + notification.getKey())) .build(new CacheLoader<String, String>() { @Override public String load(String key) { return "Computed: " + key.toUpperCase(); } });
// 写入 cache.put("key1", "value1");
// 带自动加载的读取 String value = cache.get("key2"); System.out.println(value); // "Computed: KEY2" }}2. 使用 Redis 进行分布式缓存
Redis 是一