@TestpublicvoidtestCacheBuilder()throwsExecutionException{LoadingCache<String,String>graphs=CacheBuilder.newBuilder().maximumSize(1000).build(newCacheLoader<String,String>(){publicStringload(Stringkey){// 这里是key根据实际去取值的方法,例如根据这个key去数据库或者properties文件中取值ApplicationContextcontext=newFileSystemXmlApplicationContext("E:/WorkDir/struts2practice/GuavaTest/WebRoot/WEB-INF/xml/springConfig.xml");JdbcCustomerDAOaJdbcCustomerDAO=context.getBean(JdbcCustomerDAO.class);System.out.println("load method has been invoked");returnaJdbcCustomerDAO.findValue(key);}});StringresultVal=graphs.get("testKey");System.out.println("first time value is: "+resultVal);StringresultVal1=graphs.get("testKey");System.out.println("second time values is: "+resultVal1);}
其次是基于实现callable的方法:
12345678910111213141516171819202122232425
@TestpublicvoidtestCallable()throwsExecutionException{// 没有使用CacheLoaderCache<String,String>cache=CacheBuilder.newBuilder().maximumSize(1000).build();StringresultVal=cache.get("testKey",newCallable<String>(){publicStringcall(){// 这里先根据key实际去取值的方法,例如根据这个key去数据库或者properties文件中取值ApplicationContextcontext=newFileSystemXmlApplicationContext("E:/WorkDir/struts2practice/GuavaTest/WebRoot/WEB-INF/xml/springConfig.xml");JdbcCustomerDAOaJdbcCustomerDAO=context.getBean(JdbcCustomerDAO.class);System.out.println("resultVal call method is invoked");returnaJdbcCustomerDAO.findValue("testKey");}});System.out.println("first time value is: "+resultVal);StringresultVal1=cache.get("testKey",newCallable<String>(){publicStringcall(){// 这里先根据key实际去取值的方法,例如根据这个key去数据库或者properties文件中取值ApplicationContextcontext=newFileSystemXmlApplicationContext("E:/WorkDir/struts2practice/GuavaTest/WebRoot/WEB-INF/xml/springConfig.xml");JdbcCustomerDAOaJdbcCustomerDAO=context.getBean(JdbcCustomerDAO.class);System.out.println("resultVal1 call method is invoked");returnaJdbcCustomerDAO.findValue("testKey");}});System.out.println("second time values is: "+resultVal1);}
refresh 操作, 与evict不同, 是给key一个new value, 同时如果在refresh时有访问,那么将会返回old value, 而evict则会等待evict结束返回new value
定义refresh一般使用异步的操作
12345678910111213141516171819202122
// Some keys don't need refreshing, and we want refreshes to be done asynchronously.LoadingCache<Key,Graph>graphs=CacheBuilder.newBuilder().maximumSize(1000).refreshAfterWrite(1,TimeUnit.MINUTES).build(newCacheLoader<Key,Graph>(){publicGraphload(Keykey){// no checked exceptionreturngetGraphFromDatabase(key);}publicListenableFuture<Graph>reload(finalKeykey,GraphprevGraph){if(neverNeedsRefresh(key)){returnFutures.immediateFuture(prevGraph);}else{// asynchronous!returnListenableFutureTask.create(newCallable<Graph>(){publicGraphcall(){returngetGraphFromDatabase(key);}});}}});