单例模式,可应用于本地缓存的token,与第三方接口交互:获取token,存本地缓存,通过缓存获取数据。
1、创建单例实例类
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public class GuavaCacheUtils {
private volatile static Cache<String, String> cache;
private GuavaCacheUtils() {}
/**
* 获取一个单例实例
*
* @return
*/
public static Cache<String, String> getInstance() {
if (cache == null) {
synchronized (GuavaCacheUtils.class) {
if (cache == null) {
cache = CacheBuilder.newBuilder().build();
}
}
}
return cache;
}
}
2、存缓存
GuavaCacheUtils.getInstance().put(key+ "token", token);
3、取缓存
String accessToken = GuavaCacheUtils.getInstance().getIfPresent(key+ "token");