<dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.9.0</version> </dependency> import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; public class MyCache { private static Cache<String, Data> cache; public static void initializeCache() { cache = Caffeine.newBuilder() .maximumSize(1000) .build(); } } import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; public class MyClass { private static Cache<String, Data> cache; public static void main(String[] args) { initializeCache(); String key = "myKey"; Data data = getData(key); System.out.println(data); } public static void initializeCache() { cache = Caffeine.newBuilder() .maximumSize(1000) .build(); } public static Data getData(String key) { Data data = cache.getIfPresent(key); if (data == null) { data = fetchDataFromDataSource(key); cache.put(key, data); } return data; } public static Data fetchDataFromDataSource(String key) { } } Cache<String, Data> cache = Caffeine.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .refreshAfterWrite(5, TimeUnit.MINUTES) .build();


上一篇:
下一篇:
切换中文