GuavaCache是google开源java类库Guava的其中一个模块,它简单、强大、轻量。
1.依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
2.测试本地缓存
GuavaCache也是基于key-value的存储结构,所以创建cache的时候可以根据需求创建需要的类型。
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class TestCacheBuilder {
private final static Cache<String, String> cache = CacheBuilder.newBuilder()
//设置cache的初始大小为20
.initialCapacity(20)
//设置写入并发数为5
.concurrencyLevel(5)
//设置cache中的数据存活时间为10秒
.expireAfterWrite(10, TimeUnit.SECONDS)
//构建cache实例
.build();
public static void main(String[] args) throws Exception{
cache.put("test", "cache");
for (int i = 0; i < 11; i++) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(new Date()) + " " + cache.getIfPresent("test"));
Thread.sleep(1000);
}
}
}
3.常用方法
public interface Cache<K, V> {
/**
*通过key获取value,不存在返回null
*/
V getIfPresent(Object key);
/**
* 添加缓存,key存在,覆盖
*/
void put(K key, V value);
/**
* 删除该key的缓存
*/
void invalidate(Object key);
/**
* 删除所有缓存
*/
void invalidateAll();
/**
* 清理缓存
*/
void cleanUp();
}