高性能内存缓存框架Caffeine,Java
代码:
package org.example;import com.github.benmanes.caffeine.cache.*;
import org.checkerframework.checker.nullness.qual.Nullable;import java.util.concurrent.TimeUnit;public class App {public static void main(String[] args) {try {new App().test();} catch (Exception e) {e.printStackTrace();}}private void test() {LoadingCache<String, Object> cache = Caffeine.newBuilder().maximumSize(99999) //缓存中存储的最大缓存数量,如果超出就开始根据一定策略删缓存//在写入一定时间后删掉缓存.expireAfterWrite(100, TimeUnit.SECONDS)//在访问(get)一定时间后删掉缓存.expireAfterAccess(15, TimeUnit.SECONDS)//在一定时间后刷新缓存.refreshAfterWrite(30, TimeUnit.SECONDS)//也可自定义缓存失效策略/**.expireAfter(new Expiry<Object, Object>() {@Override public long expireAfterCreate(Object o, Object o2, long l) {return 0;}@Override public long expireAfterUpdate(Object o, Object o2, long l, @NonNegative long l1) {return 0;}@Override public long expireAfterRead(Object o, Object o2, long l, @NonNegative long l1) {return 0;}})*///删除缓存监听事件.removalListener(new RemovalListener<Object, Object>() {@Overridepublic void onRemoval(@Nullable Object o, @Nullable Object o2, RemovalCause removalCause) {System.out.println(o + " remove reason ==> " + removalCause);}}).build(new CacheLoader<String, Object>() {@Overridepublic @Nullable Object load(String s) throws Exception {return "new data load";}});String NAME = "name";cache.put(NAME, "zhangphil");//获取缓存值,如果为空,返回nullSystem.out.println(cache.getIfPresent(NAME).toString());//使NAME这一条缓存失效。cache.invalidate(NAME);//cache.invalidateAll(); //使所有缓存失效。System.out.println(cache.getIfPresent(NAME) + "");try {Thread.sleep(10);} catch (InterruptedException e) {throw new RuntimeException(e);}}
}
输出:
zhangphil
null
name remove reason ==> EXPLICIT
Caffeine 开源地址:
GitHub - ben-manes/caffeine: A high performance caching library for JavaA high performance caching library for Java. Contribute to ben-manes/caffeine development by creating an account on GitHub.https://github.com/ben-manes/caffeine
Caffeine maven库地址:
https://maven-badges.herokuapp.com/maven-central/com.github.ben-manes.caffeine/caffeinehttps://maven-badges.herokuapp.com/maven-central/com.github.ben-manes.caffeine/caffeine