import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.concurrent.TimeUnit;
public class HotspotCache {
private final LoadingCache<String, String> cache;
public HotspotCache() {
cache = CacheBuilder.newBuilder()
.maximumSize(1000) // 设置缓存的最大条数
.expireAfterWrite(10, TimeUnit.MINUTES) // 设置缓存的过期时间
.build(new CacheLoader<String, String>() {
// 定义如何加载数据到缓存
@Override
public String load(String key) throws Exception {
return fetchDataFromDatabase(key);
}
});
}
public String get(String key) throws Exception {
return cache.get(key); // 尝试从缓存获取数据,如果没有则加载数据到缓存
}
private String fetchDataFromDatabase(String key) {
// 实现从数据库获取数据的逻辑
return "data";
}
}
public class Main {
public static void main(String[] args) {
HotspotCache cache = new HotspotCache();
try {
String data = cache.get("hotspotKey");
// 使用缓存中的数据
} catch (Exception e) {
e.printStackTrace();
}
}
}
扩展查看: