Guava Cache使用笔记
编程技术  /  houtizong 发布于 3年前   215
public enum TestGuavaCache { INSTANCE; private LoadingCache<String, Person> infos; TestGuavaCache() { infos = CacheBuilder.newBuilder().expireAfterAccess(10, TimeUnit.MINUTES).build(new CacheLoader<String, Person>() { public Person load(String key) throws Exception { //load from database Person p = loadFromDatabase(); return p; } }); }//假设数据库中不存在 private Person loadFromDatabase() { return null; } public Person get(String key) { try { return infos.get(key); } catch (Exception e) { //log exception } return null; }}
@Testpublic void whenNullValue_thenOptional() { CacheLoader<String, Optional<String>> loader; loader = new CacheLoader<String, Optional<String>>() { @Override public Optional<String> load(String key) { return Optional.fromNullable(getSuffix(key)); } }; LoadingCache<String, Optional<String>> cache; cache = CacheBuilder.newBuilder().build(loader); assertEquals("txt", cache.getUnchecked("text.txt").get()); assertFalse(cache.getUnchecked("hello").isPresent());}private String getSuffix(final String str) { int lastIndex = str.lastIndexOf('.'); if (lastIndex == -1) { return null; } return str.substring(lastIndex + 1);}
. If you have defined a CacheLoader that does not declare any checked exceptions then you can perform cache lookups using getUnchecked(K); however care must be taken not to call getUnchecked on caches whose CacheLoaders declare checked exceptions.
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder() .expireAfterAccess(10, TimeUnit.MINUTES) .build( new CacheLoader<Key, Graph>() { public Graph load(Key key) { // no checked exception return createExpensiveGraph(key); } });...return graphs.getUnchecked(key);
com.google.common.cache.Cache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).build();
Timed expiration is performed with periodic maintenance during writes and occasionally during reads, as discussed below.Caches built with CacheBuilder do not perform cleanup and evict values "automatically," or instantly after a value expires, or anything of the sort. Instead, it performs small amounts of maintenance during write operations, or during occasional read operations if writes are rare.
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接