谷歌开源的工具库,其Cache来源于jdk7的ConcurrentHashMap(jdk8的ConcurrentHashMap引入了红黑树)。
少量的数据缓存可以直接使用包装类,List、hashmap等。
如果希望数据存储的空间是可控的,并且改变结果,使用这种方法是推荐的。
首先pom里引入google的guava包。
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
代码里有注释,不作更多说明
@Slf4j
public class GuavaCache1 {
public static void main(String[] args) {
LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
.maximumSize(10)//最多存放10个数据
.expireAfterWrite(10, TimeUnit.SECONDS)//缓存10s
.recordStats()//开启记录数据功能
.build(new CacheLoader<String, Integer>() {
@Override
public Integer load(String s) throws Exception {
//当数据不存在时使用get()返回-1
return -1;
}
});
log.info("{}", cache.getIfPresent("key1"));//null
cache.put("key1", 1);
log.info("{}", cache.getIfPresent("key1"));//1
cache.invalidate("key1");
log.info("{}", cache.getIfPresent("key1"));//null
try {
log.info("{}",cache.get("key2") );//-1
cache.put("key2",2 );
log.info("{}",cache.get("key2") );//2
log.info("{}",cache.size() );//1
for (int i = 3; i < 13; i++) {
cache.put("key"+i,i );
}
log.info("{}",cache.size() );//10
//最大缓存为10,计算过期时间,将时间最长的去掉
log.info("{}",cache.getIfPresent("key2") );//null
log.info("{}",cache.get("key2") );//-1
//时间大于10s,缓存过期
Thread.sleep(11000);
log.info("{}",cache.getIfPresent("key5") );//null
//针对读操作,一个缓存还没有被读取就失效了,低命中,缓存效果差命中次数,丢失次数
log.info("{},{}",cache.stats().hitCount(),cache.stats().missCount() );//2,5
//命中率 ,丢失率
log.info("{},{}",cache.stats().hitRate(),cache.stats().missRate() );
} catch (Exception e) {
log.error("cache exception", e);
}
}
}
@Slf4j
public class GuavaCache2 {
public static void main(String[] args) {
Cache<String, Integer> cache = CacheBuilder.newBuilder()
.maximumSize(10)//最多存放10个数据
.expireAfterWrite(10, TimeUnit.SECONDS)//缓存10s
.recordStats()//开启记录状态数据功能
.build();
log.info("{}", cache.getIfPresent("key1"));//null
cache.put("key1", 1);
log.info("{}", cache.getIfPresent("key1"));//1
cache.invalidate("key1");
log.info("{}", cache.getIfPresent("key1"));//null
try {
log.info("{}", cache.get("key2", new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return -1;
}
}));//-1
cache.put("key2", 2);
log.info("{}", cache.get("key2", new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return -1;
}
})); // 2
log.info("{}", cache.size()); // 1
for (int i = 3; i < 13; i++) {
cache.put("key" + i, i);
}
log.info("{}", cache.size()); // 10
log.info("{}", cache.getIfPresent("key2")); // null
Thread.sleep(11000);
log.info("{}", cache.get("key5", new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return -1;
}
})); // -1
log.info("{},{}", cache.stats().hitCount(), cache.stats().missCount());
log.info("{},{}", cache.stats().hitRate(), cache.stats().missRate());
} catch (Exception e) {
e.printStackTrace();
}
}
}
GuavaCache1 对get()方法返回-1,是统一配置的,而GuavaCache2每次get()都要配置一次,如果需要返回不同的值用GuavaCache2