guava是谷歌几个java核心类库的集合,包括集合、缓存、原生类型、并发、常用注解、基本字符串操作和I/O等等。
这篇文章主要说明下其中缓存部分的用法。这文章主要是我结合wiki中内容学习的一个小结:
wiki的地址如下,但是需要fan qiang访问: https://code.google.com/p/guava-libraries/wiki/CachesExplained
基本上可以通过两种方式来创建cache:
cacheLoader
callable callback
通过这两种方法创建的cache,和通常用map来缓存的做法比,不同在于,这两种方法都实现了一种逻辑——从缓存中取key X的值,如果该值已经缓存过了,则返回缓存中的值,如果没有缓存过,可以通过某个方法来获取这个值。
但不同的在于cacheloader的定义比较宽泛,是针对整个cache定义的,可以认为是统一的根据key值load value的方法。
而callable的方式较为灵活,允许你在get的时候指定。
下面是两种方法的例子:
首先是基于cacheloader的方法
@Test
public void testCacheBuilder() throws ExecutionException {
LoadingCache<String, String> graphs = CacheBuilder.newBuilder().maximumSize(1000)
.build(new CacheLoader<String, String>() {
public String load(String key) {
// 这里是key根据实际去取值的方法,例如根据这个key去数据库或者properties文件中取值
ApplicationContext context = new FileSystemXmlApplicationContext("E:/WorkDir/struts2practice/GuavaTest/WebRoot/WEB-INF/xml/springConfig.xml");
JdbcCustomerDAO aJdbcCustomerDAO = context.getBean(JdbcCustomerDAO.class);
System.out.println("load method has been invoked");
return aJdbcCustomerDAO.findValue(key);
}
});
String resultVal = graphs.get("testKey");
System.out.println("first time value is: " + resultVal);
String resultVal1 = graphs.get("testKey");
System.out.println("second time values is: " + resultVal1);
}
其次是基于实现callable的方法:
@Test
public void testCallable() throws ExecutionException {
// 没有使用CacheLoader
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();
String resultVal = cache.get("testKey", new Callable<String>() {
public String call() {
// 这里先根据key实际去取值的方法,例如根据这个key去数据库或者properties文件中取值
ApplicationContext context = new FileSystemXmlApplicationContext("E:/WorkDir/struts2practice/GuavaTest/WebRoot/WEB-INF/xml/springConfig.xml");
JdbcCustomerDAO aJdbcCustomerDAO = context.getBean(JdbcCustomerDAO.class);
System.out.println("resultVal call method is invoked");
return aJdbcCustomerDAO.findValue("testKey");
}
});
System.out.println("first time value is: " + resultVal);
String resultVal1 = cache.get("testKey", new Callable<String>() {
public String call() {
// 这里先根据key实际去取值的方法,例如根据这个key去数据库或者properties文件中取值
ApplicationContext context = new FileSystemXmlApplicationContext("E:/WorkDir/struts2practice/GuavaTest/WebRoot/WEB-INF/xml/springConfig.xml");
JdbcCustomerDAO aJdbcCustomerDAO = context.getBean(JdbcCustomerDAO.class);
System.out.println("resultVal1 call method is invoked");
return aJdbcCustomerDAO.findValue("testKey");
}
});
System.out.println("second time values is: " + resultVal1);
}