Google的Guava cache 使用
http://xpchenfrank.iteye.com/category/220687
Guava Cache 创建
基本上可以通过两种方式来创建cache:
cacheLoader
callable callback
通过这两种方法创建的cache,和通常用map来缓存的做法比,不同在于,这两种方法都实现了一种逻辑——从缓存中取key X的值,如果该值已经缓存过了,则返回缓存中的值,如果没有缓存过,可以通过某个方法来获取这个值。
但不同的在于cacheloader的定义比较宽泛,是针对整个cache定义的,可以认为是统一的根据key值load value的方法。
而callable的方式较为灵活,允许你在get的时候指定。
下面是两种方法的例子:
首先是基于cacheloader的方法
@Test public void testCacheBuilder() throws ExecutionException { LoadingCache<String, Book> cache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(3, TimeUnit.SECONDS).build(new CacheLoader<String, Book>(){@Overridepublic Book load(String key) throws Exception {Book b = new Book();return b;}});Book book = cache.get("testKey"); System.out.println("1 time value is: " + book); Thread.currentThread(); Thread.sleep(TimeUnit.SECONDS.toMillis(2)); //还是在3秒之内读取 Book book1 = cache.get("testKey"); System.out.println("2 time value is: " + book1); Thread.currentThread(); Thread.sleep(TimeUnit.SECONDS.toMillis(3)); //第二次读取的时候继续缓存3秒计算。到这里的时候刚好是3秒,就是说超时读取,会得到新对象。当这里是toMillis(2)的话,还是在3秒缓存之内,就会得到旧内容的。 Book book2 = cache.get("testKey"); System.out.println("6 time value is: " + book2);} } @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); } LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder() .maximumSize(1000) .refreshAfterWrite(1, TimeUnit.MINUTES) .build( new CacheLoader<Key, Graph>() { public Graph load(Key key) { // no checked exception return getGraphFromDatabase(key); } public ListenableFuture<Graph> reload(final Key key, Graph prevGraph) { if (neverNeedsRefresh(key)) { return Futures.immediateFuture(prevGraph); } else { // asynchronous! return ListenableFutureTask.create(new Callable<Graph>() { public Graph call() { return getGraphFromDatabase(key); } }); } } });