高性能内存缓存框架Caffeine,Java
Posted zhangphil
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了高性能内存缓存框架Caffeine,Java相关的知识,希望对你有一定的参考价值。
高性能内存缓存框架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>()
@Override
public void onRemoval(@Nullable Object o, @Nullable Object o2, RemovalCause removalCause)
System.out.println(o + " remove reason ==> " + removalCause);
)
.build(new CacheLoader<String, Object>()
@Override
public @Nullable Object load(String s) throws Exception
return "new data load";
);
String NAME = "name";
cache.put(NAME, "zhangphil");
//获取缓存值,如果为空,返回null
System.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 开源地址:
Caffeine maven库地址:
以上是关于高性能内存缓存框架Caffeine,Java的主要内容,如果未能解决你的问题,请参考以下文章