package com.mmall.common;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* Created by 敲代碼的卡卡羅特
* on 2018/3/11 16:52.
*/
@Slf4j
public class TokenCache {
public static final String TOKEN_PREFIX="token_";
private static LoadingCache<String,String> loadingCache = CacheBuilder.newBuilder().initialCapacity(1000)//初始容量
.maximumSize(10000) //最大緩存數據量
.expireAfterAccess(12, TimeUnit.HOURS) //過期清除
.removalListener(new RemovalListener<String, String>() { //設置監聽事件,就是在 刪除key的時候觸發這個事件
@Override
public void onRemoval(RemovalNotification<String, String> notification) {
System.out.println(registerCache.size()+"---------------");
String email = notification.getValue();
String key = notification.getKey();
RemovalCause cause = notification.getCause();
System.out.println("email===="+email);
System.out.println("key===="+key);
System.out.println("cause===="+cause);
}
})
.build(new CacheLoader<String, String>() { //緩存規則,功能很雞肋 不知道干嘛的 沒用到過。
@Override
public String load(String s) throws Exception {
return "null";
}
});
public static void setKey(String key,String val){
loadingCache.put(key,val);
}
public static String getKey(String key){
String val=null;
try {
val = loadingCache.get(key);
} catch (ExecutionException e) {
e.printStackTrace();
log.error("緩存中沒有該key");
}
return val;
}
//刪除key的幾個方法
//任何時候,你都可以顯式地清除緩存項,而不是等到它被回收:
//個別清除:Cache.invalidate(key)
//批量清除:Cache.invalidateAll(keys)
//清除所有緩存項:Cache.invalidateAll()
}