下面是使用 Google 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 {
private static final int CACHE_MAX_SIZE = 1000;
private static final int CACHE_EXPIRATION_MINUTES = 5;
public static void main(String[] args) throws ExecutionException {
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(CACHE_MAX_SIZE)
.expireAfterWrite(CACHE_EXPIRATION_MINUTES, TimeUnit.MINUTES)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) {
// 假设这里从数据库中获取数据
return "Value for " + key;
}
});
// 缓存中没有 key 对应的数据时,通过 CacheLoader 从数据库中获取并放入缓存中
String value1 = cache.get("Key1");
System.out.println(value1); // Output: Value for Key1
// 再次获取已存在于缓存中的数据,直接从缓存中获取
String value2 = cache.get("Key1");
System.out.println(value2); // Output: Value for Key1
// 缓存过期后重新从 CacheLoader 获取数据
Thread.sleep(6 * 60 * 1000);
String value3 = cache.get("Key1");
System.out.println(value3); // Output: Value for Key1
}
}
在上述代码中,我们使用 CacheBuilder 创建了一个缓存对象,并将其配置为最大容量为 CACHE_MAX_SIZE
个键值对,过期时间为 CACHE_EXPIRATION_MINUTES
分钟。同时,我们通过 CacheLoader 实现了从数据库中获取数据的逻辑。在使用时,我们通过 cache.get(key) 方法来获取缓存中对应的数据,如果缓存中不存在该数据,则会调用 CacheLoader 的 load(key) 方法从数据库中读取并放入缓存中,之后再次调用 cache.get(key) 方法时则直接从缓存中获取数据。通过这种方式,我们可以方便地实现基于 Guava 的本地缓存。