缓存和数据库的区别,缓存之缓存之缓存的使用场景
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
public class DataCache {
private Cache<String, String> cache;
public DataCache() {
cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(1000)
.build();
}
public String getData(String key) {
return cache.get(key, k -> fetchDataFromDataSource(k));
}
private String fetchDataFromDataSource(String key) {
// 从数据库或其他数据源获取数据
return "Data for " + key;
}
}