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() }