guava是谷歌提供的工具类,功能强大,举个例子,我我想把数据存到本地,该咋办?我们想到的只有是全局的Map和session中。如果我们想实现这个容器的大小呢?时间呢?不好搞吧。
guava就有这样的功能。话不多说 上code
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
TokenCache.java
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() }
 
 
 
05-11 04:22
查看更多