Caffeine Cache CRUD
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/15002781.html
Maven Dependency
... <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.9.2</version> </dependency> ...
SRC
package org.fool.cache; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.RemovalCause; import com.github.benmanes.caffeine.cache.RemovalListener; import lombok.extern.slf4j.Slf4j; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; @Slf4j public class CaffeineCacheService { private static final Cache<String, String> CACHE = Caffeine.newBuilder() .maximumSize(100) .expireAfterAccess(5, TimeUnit.SECONDS) .removalListener(new RemovalListener<String, String>() { @Override public void onRemoval(@Nullable String key, @Nullable String value, @NonNull RemovalCause removalCause) { log.info("removing cache: {{}:{}}", key, value); } }) .build(); /** * 获取缓存值 */ public static String get(String key, boolean hasDefaultReturn) { try { String value = hasDefaultReturn ? CACHE.get(key, v -> "test_" + v) : CACHE.getIfPresent(key); log.info("get cache with key: {}, value: {}", key, value); return value; } catch (Exception e) { log.error("get cache data error with key: {}", key, e); } return null; } /** * 移除缓存 */ public static void remove(String key) { try { log.info("remove cache with key: {}", key); CACHE.invalidate(key); } catch (Exception e) { log.error("remove cache data error with key: {}", key, e); } } /** * 清空缓存内数据 */ public static void removeAll() { log.info("remove all cache"); CACHE.invalidateAll(); } /** * 设置缓存值 * 注: 若已有该key值,则会先移除(会触发removalListener移除监听器),再添加 */ public static void add(String key, String value) { CACHE.put(key, value); log.info("add cache with key: {}, value: {}", key, value); } /** * 查看缓存中内容 */ public static ConcurrentMap<String, String> getAll() { log.info("get all cache: {}", CACHE.asMap()); return CACHE.asMap(); } public static void main(String[] args) throws Exception { add("abc", "abcval"); get("abc", false); add("abc", "xyzval"); get("abc", false); getAll(); System.out.println("===start sleep==="); Thread.sleep(10000); System.out.println("===end sleep==="); getAll(); get("cache1", false); get("cache2", true); get("cache3", true); getAll(); remove("cache2"); getAll(); removeAll(); getAll(); } }
Console Output
Reference
https://www.baeldung.com/java-caching-caffeine
欢迎点赞关注和收藏
强者自救 圣者渡人