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).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; } }