guava cache使用例子

关于介绍请参考:http://blog.csdn.net/liangrui1988/article/details/46120533#

下面是测试代码 ,下载源码可在github上获取:https://github.com/liangrui1988/guavaTest

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package org.rui.test;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutionException;  
  5.   
  6. import org.junit.Test;  
  7.   
  8. import com.google.common.cache.Cache;  
  9. import com.google.common.cache.CacheBuilder;  
  10. import com.google.common.cache.CacheLoader;  
  11. import com.google.common.cache.LoadingCache;  
  12. import com.google.common.cache.Weigher;  
  13.   
  14. /** 
  15.  *  Guava Cache有两种创建方式: 
  16.  *  
  17.  *   1. cacheLoader   2. callable callback 
  18.  *  
  19.  *   通过这两种方法创建的cache,和通常用map来缓存的做法比,不同在于,这两种方法都实现了一种逻辑——从缓存中取key 
  20.  * X的值,如果该值已经缓存过了,则返回缓存中的值 
  21.  * ,如果没有缓存过,可以通过某个方法来获取这个值。但不同的在于cacheloader的定义比较宽泛,是针对整个cache定义的 
  22.  * ,可以认为是统一的根据key值load value的方法。而callable的方式较为灵活,允许你在get的时候指定。 
  23.  *  
  24.  * @author liangrui 
  25.  * 
  26.  */  
  27. public class Tests  
  28. {  
  29.   
  30.     /** 
  31.      * CacheLoader 
  32.      */  
  33.     @Test  
  34.     public void loadingCache()  
  35.     {  
  36.         LoadingCache<String, String> graphs = CacheBuilder.newBuilder()  
  37.                 .maximumSize(1000).build(new CacheLoader<String, String>()  
  38.                 {  
  39.                     @Override  
  40.                     public String load(String key) throws Exception  
  41.                     {  
  42.                         System.out.println("key:"+key);  
  43.                         if("key".equals(key)){  
  44.                             return "key return result";  
  45.                         }else{  
  46.                             return "get-if-absent-compute";  
  47.                         }  
  48.                           
  49.                           
  50.                     }  
  51.   
  52.                 });  
  53.   
  54.         String resultVal = null;  
  55.         try {  
  56.             resultVal = graphs.get("key");  
  57.         } catch (ExecutionException e) {  
  58.             e.printStackTrace();  
  59.         }  
  60.           
  61.         System.out.println(resultVal);  
  62.     }  
  63.   
  64.     /** 
  65.      *  
  66.      * Callable 
  67.      * 在使用缓存前,首先问自己一个问题:有没有合理的默认方法来加载或计算与键关联的值?如果有的话,你应当使用CacheLoader。如果没有, 
  68.      * 或者你想要覆盖默认的加载运算,同时保留"获取缓存-如果没有-则计算"[get-if-absent-compute]的原子语义, 
  69.      * 你应该在调用get时传入一个Callable实例 
  70.      * 。缓存元素也可以通过Cache.put方法直接插入,但自动加载是首选的,因为它可以更容易地推断所有缓存内容的一致性。 
  71.      */  
  72.     @Test  
  73.     public void callablex() throws ExecutionException  
  74.     {  
  75.   
  76.         Cache<String, String> cache = CacheBuilder.newBuilder()  
  77.                 .maximumSize(1000).build();  
  78.   
  79.         String result = cache.get("key"new Callable<String>()  
  80.         {  
  81.             public String call()  
  82.             {  
  83.                 return "result";  
  84.             }  
  85.         });  
  86.         System.out.println(result);  
  87.     }  
  88.   
  89.     /** 
  90.      * 从LoadingCache查询的正规方式是使用get(K)方法。这个方法要么返回已经缓存的值,要么使用CacheLoader向缓存原子地加载新值。 
  91.      * 由于CacheLoader可能抛出异常,LoadingCache.get(K)也声明为抛出ExecutionException异常。 
  92.      * 如果你定义的CacheLoader没有声明任何检查型异常 
  93.      * ,则可以通过getUnchecked(K)查找缓存;但必须注意,一旦CacheLoader声明了检查型异常 
  94.      * ,就不可以调用getUnchecked(K)。 
  95.      *  
  96.      * @throws ExecutionException 
  97.      */  
  98.     @Test  
  99.     public void capacity()  
  100.     {  
  101.         LoadingCache<String, String> graphs = CacheBuilder.newBuilder()  
  102.                 .maximumWeight(100000).weigher(new Weigher<String, String>()  
  103.                 {  
  104.                     public int weigh(String k, String g)  
  105.                     {  
  106.                         return 100;  
  107.                     }  
  108.                 }).build(new CacheLoader<String, String>()  
  109.                 {  
  110.                     public String load(String key)  
  111.                     { // no checked exception  
  112.                         // return createExpensiveGraph(key);  
  113.                         return "xxxx";  
  114.                     }  
  115.                 });  
  116.   
  117.     }  
  118. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package org.rui.test;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutionException;  
  5. import java.util.concurrent.TimeUnit;  
  6.   
  7. import org.junit.Test;  
  8.   
  9. import com.google.common.cache.Cache;  
  10. import com.google.common.cache.CacheBuilder;  
  11. import com.google.common.cache.CacheStats;  
  12. import com.google.common.cache.RemovalListener;  
  13. import com.google.common.cache.RemovalNotification;  
  14. import com.google.common.cache.Weigher;  
  15.   
  16. /** 
  17.  * cache的参数说明: 
  18.  *  
  19.  *   回收的参数:   1. 大小的设置:CacheBuilder.maximumSize(long) 
  20.  * CacheBuilder.weigher(Weigher) CacheBuilder.maxumumWeigher(long)   2. 
  21.  * 时间:expireAfterAccess(long, TimeUnit) expireAfterWrite(long, TimeUnit)   3. 
  22.  * 引用:CacheBuilder.weakKeys() CacheBuilder.weakValues() 
  23.  * CacheBuilder.softValues()   4. 明确的删除:invalidate(key) invalidateAll(keys) 
  24.  * invalidateAll()   5. 删除监听器:CacheBuilder.removalListener(RemovalListener)    
  25.  *  
  26.  *   refresh机制:   1. LoadingCache.refresh(K) 在生成新的value的时候,旧的value依然会被使用。   2. 
  27.  * CacheLoader.reload(K, V) 生成新的value过程中允许使用旧的value   3. 
  28.  * CacheBuilder.refreshAfterWrite(long, TimeUnit) 自动刷新cache 
  29.  * 
  30.  * 
  31.  */  
  32. public class Eviction  
  33. {  
  34.   
  35.     /** 
  36.      * 基于容量的回收 
  37.      * 
  38.      * 
  39.      * maximumSize(1) 缓存将尝试回收最近没有使用或总体上很少使用的缓存项 
  40.      *  
  41.      * 不同的缓存项有不同的“权重”(weights)——例如,如果你的缓存值 
  42.      * ,占据完全不同的内存空间,你可以使用CacheBuilder.weigher(Weigher)指定一个权重函数 
  43.      *  
  44.      */  
  45.   
  46.     @Test  
  47.     public void callablex() throws ExecutionException, InterruptedException  
  48.     {  
  49.         // .maximumSize(100)  
  50.         Cache<String, User2> cache = CacheBuilder.newBuilder().maximumWeight(5)  
  51.                 .weigher(new Weigher<String, User2>()  
  52.                 {  
  53.                     @Override  
  54.                     public int weigh(String arg0, User2 user)  
  55.                     {  
  56.                         return 3;  
  57.                     }  
  58.                 }).removalListener(new RemovalListener<String, User2>()  
  59.                 {  
  60.                     @Override  
  61.                     public void onRemoval(RemovalNotification<String, User2> rn)  
  62.                     {  
  63.                         System.out.println(rn.getKey() + "==被移除");  
  64.                     }  
  65.   
  66.                 }).build();  
  67.   
  68.         User2 result = cache.get("key"new Callable<User2>()  
  69.         {  
  70.             public User2 call()  
  71.             {  
  72.                 return new User(1"liang");  
  73.             }  
  74.         });  
  75.   
  76.         // Thread.sleep(10000);  
  77.   
  78.         User result2 = (User) cache.get("key2"new Callable<User2>()  
  79.         {  
  80.             public User2 call()  
  81.             {  
  82.                 return new User(2"liang2");  
  83.             }  
  84.         });  
  85.   
  86.         User result3 = (User) cache.get("key3"new Callable<User>()  
  87.         {  
  88.             public User call()  
  89.             {  
  90.                 return new User(3"liang3");  
  91.             }  
  92.         });  
  93.   
  94.         System.out.println(result);  
  95.         System.out.println(result2);  
  96.         System.out.println(result3);  
  97.         System.out.println(cache.size());  
  98.     }  
  99.   
  100.     /** 
  101.      *  
  102.      *  
  103.      * 定时回收(Timed Eviction) expireAfterAccess(long, 
  104.      * TimeUnit):缓存项在给定时间内没有被读/写访问,则回收。请注意这种缓存的回收顺序和基于大小回收一样。 
  105.      * expireAfterWrite(long, 
  106.      * TimeUnit):缓存项在给定时间内没有被写访问(创建或覆盖),则回收。如果认为缓存数据总是在固定时候后变得陈旧不可用,这种回收方式是可取的。 
  107.      *  
  108.      *  
  109.      *  
  110.      * // .expireAfterWrite(5, TimeUnit.SECONDS)//给定时间内没有写访问,则回收。 27 // 
  111.      * .expireAfterAccess(3, TimeUnit.SECONDS)// 缓存过期时间为3秒 
  112.      *  
  113.      * @param args 
  114.      */  
  115.   
  116.     Cache<String, User2> cache2 = CacheBuilder.newBuilder().maximumSize(100)  
  117.             .expireAfterWrite(3, TimeUnit.MILLISECONDS)  
  118.             // .expireAfterAccess(3000, TimeUnit.MILLISECONDS)  
  119.             .removalListener(new RemovalListener<String, User2>()  
  120.             {  
  121.                 @Override  
  122.                 public void onRemoval(RemovalNotification<String, User2> rn)  
  123.                 {  
  124.                     System.out.println("Cause:" + rn.getCause() + " k: "  
  125.                             + rn.getKey() + " v :" + rn.getValue() + "==被移除");  
  126.                 }  
  127.   
  128.             }).build();  
  129.   
  130.     @Test  
  131.     public void timerEvication() throws ExecutionException,  
  132.             InterruptedException  
  133.     {  
  134.   
  135.         User2 user = cache2.get("k1"new Callable<User2>()  
  136.         {  
  137.             @Override  
  138.             public User2 call() throws Exception  
  139.             {  
  140.   
  141.                 return new User(100"hello");  
  142.             }  
  143.         });  
  144.         Thread.sleep(8000);  
  145.         System.out.println(cache2.size());  
  146.   
  147.         User2 user2 = cache2.get("k2"new Callable<User2>()  
  148.         {  
  149.             @Override  
  150.             public User2 call() throws Exception  
  151.             {  
  152.   
  153.                 return new User(200"hello2");  
  154.             }  
  155.         });  
  156.         System.out.println(user);  
  157.         Thread.sleep(8000);  
  158.         user = cache2.get("k1"new Callable<User2>()  
  159.         {  
  160.             @Override  
  161.             public User2 call() throws Exception  
  162.             {  
  163.   
  164.                 return new User(10000000"k1k1k1k1k1k1k1");  
  165.             }  
  166.         });  
  167.   
  168.         System.out.println(cache2.size());  
  169.   
  170.         User2 user3 = cache2.get("k3"new Callable<User2>()  
  171.         {  
  172.             @Override  
  173.             public User2 call() throws Exception  
  174.             {  
  175.   
  176.                 return new User(300"hello3");  
  177.             }  
  178.         });  
  179.   
  180.         System.out.println(user);  
  181.         System.out.println(user2);  
  182.         System.out.println(user3);  
  183.   
  184.         Thread.sleep(10000);  
  185.         System.out.println(cache2.size());  
  186.         CacheStats status = cache2.stats();  
  187.         status.missCount();  
  188.   
  189.     }  
  190.   
  191.     /** 
  192.      * 显式清除 
  193.      *  
  194.      * 任何时候,你都可以显式地清除缓存项,而不是等到它被回收: 
  195.      *  
  196.      * 个别清除:Cache.invalidate(key) 批量清除:Cache.invalidateAll(keys) 
  197.      * 清除所有缓存项:Cache.invalidateAll() 
  198.      *  
  199.      * @param args 
  200.      */  
  201.   
  202.     Cache<String, User2> cache3 = CacheBuilder.newBuilder().maximumSize(100)  
  203.             .removalListener(new RemovalListener<String, User2>()  
  204.             {  
  205.                 @Override  
  206.                 public void onRemoval(RemovalNotification<String, User2> rn)  
  207.                 {  
  208.                     System.out.println("Cause:" + rn.getCause() + " k: "  
  209.                             + rn.getKey() + " v :" + rn.getValue() + "==被移除");  
  210.                 }  
  211.   
  212.             }).build();  
  213.   
  214.     @Test  
  215.     public void clear() throws ExecutionException  
  216.     {  
  217.   
  218.         User2 u = cache3.get("u1"new Callable<User2>()  
  219.         {  
  220.             @Override  
  221.             public User2 call() throws Exception  
  222.             {  
  223.                 System.out.println("exec call>>>return result");  
  224.                 return new User(500"world");  
  225.             }  
  226.         });  
  227.   
  228.         System.out.println(u);  
  229.   
  230.         u = cache3.get("u1"new Callable<User2>()  
  231.         {  
  232.             @Override  
  233.             public User2 call() throws Exception  
  234.             {  
  235.                 System.out.println("exec call>>>return result");  
  236.                 return new User(500"world");  
  237.             }  
  238.         });  
  239.         System.out.println(u);  
  240.         cache3.invalidate("u1");  
  241.         u = cache3.get("u1"new Callable<User2>()  
  242.         {  
  243.             @Override  
  244.             public User2 call() throws Exception  
  245.             {  
  246.                 System.out.println("exec call>>>return result");  
  247.                 return new User(500"world");  
  248.             }  
  249.         });  
  250.           
  251.           
  252.           
  253.           
  254.     }  
  255.   
  256. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package org.rui.test;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutionException;  
  5. import java.util.concurrent.Executor;  
  6. import java.util.concurrent.TimeUnit;  
  7.   
  8. import com.google.common.cache.CacheBuilder;  
  9. import com.google.common.cache.CacheLoader;  
  10. import com.google.common.cache.LoadingCache;  
  11. import com.google.common.util.concurrent.Futures;  
  12. import com.google.common.util.concurrent.ListenableFuture;  
  13. import com.google.common.util.concurrent.ListenableFutureTask;  
  14.   
  15. /** 
  16.  * 刷新和回收不太一样。正如LoadingCache.refresh(K)所声明,刷新表示为键加载新值,这个过程可以是异步的。在刷新操作进行时, 
  17.  * 缓存仍然可以向其他线程返回旧值,而不像回收操作,读缓存的线程必须等待新值加载完成。 
  18.  *  
  19.  * 如果刷新过程抛出异常,缓存将保留旧值,而异常会在记录到日志后被丢弃 
  20.  *  
  21.  * @author lenovo 
  22.  * 
  23.  */  
  24. public class Refresh  
  25. {  
  26.   
  27.     static int ixs = 0;  
  28.   
  29.     public static void main(String[] args) throws InterruptedException,  
  30.             ExecutionException  
  31.     {  
  32.   
  33.         LoadingCache<String, String> graphs = CacheBuilder.newBuilder()  
  34.                 .maximumSize(1000).refreshAfterWrite(1, TimeUnit.MICROSECONDS)  
  35.                 .build(new CacheLoader<String, String>()  
  36.                 {  
  37.                     @Override  
  38.                     public ListenableFuture<String> reload(final String key,  
  39.                             String oldValue) throws Exception  
  40.                     {  
  41.                         System.out.println("oldValue:" + oldValue);  
  42.                         ixs++;  
  43.                         if (key.equals("keyx")) {  
  44.                             return Futures.immediateFuture("new Values_" + ixs);  
  45.                         } else {  
  46.   
  47.                             ListenableFutureTask<String> taks = ListenableFutureTask  
  48.                                     .create(new Callable<String>()  
  49.                                     {  
  50.                                         @Override  
  51.                                         public String call() throws Exception  
  52.                                         {  
  53.                                             return key + " xxxxxx_" + ixs;  
  54.                                         }  
  55.                                     });  
  56.                             Executor executor = new ExecutorImple();  
  57.                             executor.execute(taks);  
  58.                             return taks;  
  59.                         }  
  60.   
  61.                     }  
  62.   
  63.                     @Override  
  64.                     public String load(String arg0) throws Exception  
  65.                     {  
  66.                         return "get-if-absent-compute_" + ixs;  
  67.                     }  
  68.   
  69.                 });  
  70.   
  71.         String resultVal = null;  
  72.   
  73.         resultVal = graphs.get("key");  
  74.   
  75.         System.out.println(resultVal);  
  76.         Thread.sleep(2000);  
  77.         resultVal = graphs.get("key");  
  78.         System.out.println(resultVal);  
  79.         Thread.sleep(2000);  
  80.         resultVal = graphs.get("key");  
  81.         System.out.println(resultVal);  
  82.         Thread.sleep(5000);  
  83.         resultVal = graphs.get("key");  
  84.         System.out.println(resultVal);  
  85.     }  
  86. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package org.rui.test;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.Set;  
  5. import java.util.concurrent.Callable;  
  6. import java.util.concurrent.ExecutionException;  
  7.   
  8. import org.junit.Test;  
  9.   
  10. import com.google.common.cache.Cache;  
  11. import com.google.common.cache.CacheBuilder;  
  12. import com.google.common.cache.CacheStats;  
  13.   
  14. /** 
  15.  * 统计 信息 
  16.  *  
  17.  * @author lenovo 
  18.  * 
  19.  */  
  20. public class RecordStatus  
  21. {  
  22.     Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(2)  
  23.             .recordStats().build();  
  24.   
  25.     @Test  
  26.     public void loadCached() throws ExecutionException  
  27.     {  
  28.         String result = cache.get("key"new Callable<String>()  
  29.         {  
  30.             public String call()  
  31.             {  
  32.                 return "result";  
  33.             }  
  34.         });  
  35.   
  36.         String result2 = cache.get("key2"new Callable<String>()  
  37.         {  
  38.             public String call()  
  39.             {  
  40.                 return "result2";  
  41.             }  
  42.         });  
  43.   
  44.         String result3 = cache.get("key3"new Callable<String>()  
  45.         {  
  46.             public String call()  
  47.             {  
  48.                 return "result3";  
  49.             }  
  50.         });  
  51.   
  52.         result = cache.get("key"new Callable<String>()  
  53.         {  
  54.             public String call()  
  55.             {  
  56.                 return "result";  
  57.             }  
  58.         });  
  59.   
  60.         System.out.println(result);  
  61.         System.out.println(result2);  
  62.         System.out.println(result3);  
  63.         System.out.println(cache.getIfPresent("key"));  
  64.   
  65.         //  
  66.         CacheStats cstats = cache.stats();  
  67.         System.out.println("loadCount:" + cstats.loadCount()  
  68.                 + "  loadSuccessCount: " + cstats.loadSuccessCount());  
  69.   
  70.         System.out.println("缓存命中率:" + cstats.hitRate() + " hitCount: "  
  71.                 + cstats.hitCount());// 缓存命中率;  
  72.         System.out.println("加载新值的平均时间:" + cstats.averageLoadPenalty() + " 纳秒");// 加载新值的平均时间,单位为纳秒;  
  73.         System.out.println("缓存项被回收的总数:" + cstats.evictionCount());// 缓存项被回收的总数,不包括显式清除。  
  74.         System.out.println();  
  75.   
  76.         // cache.asMap().entrySet()  
  77.         Set<String> set = cache.asMap().keySet();// 所有健  
  78.         Iterator<String> it = set.iterator();  
  79.         System.out.println("all key====");  
  80.         while (it.hasNext()) {  
  81.   
  82.             System.out.print(it.next() + " \t ");  
  83.         }  
  84.         System.out.println();  
  85.   
  86.     }  
  87.   
  88. }  

下面是本人自已的想法,还没正实可用性,仅参考





[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package org.rui.utils;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutionException;  
  5.   
  6. import com.google.common.cache.Cache;  
  7.   
  8. /**  
  9.  * guava cached 共公接口  
  10.  *   
  11.  * @author liangrui  
  12.  * @date 2015/6/7  
  13.  * @param <K>  
  14.  * @param <V>  
  15.  */  
  16. public interface ICached<K, V>  
  17. {  
  18.     /**  
  19.      * callable 获取cached 方式  
  20.      *   
  21.      * @param key  
  22.      * @param callable  
  23.      * @return  
  24.      * @throws ExecutionException  
  25.      */  
  26.     V getCallable(K key, Callable<V> callable) throws ExecutionException;  
  27.   
  28.     /**  
  29.      * cachedLoader 获取方式  
  30.      *   
  31.      * @param key  
  32.      * @return  
  33.      * @throws ExecutionException  
  34.      */  
  35.     V getLoader(K key) throws ExecutionException;  
  36.   
  37.     /**  
  38.      * 获取某一项的 缓存  
  39.      *   
  40.      * @param Cached  
  41.      * @return  
  42.      */  
  43.     Cache getCache(String Cached);  
  44.   
  45.     /**  
  46.      * 获取所有guava 缓存  
  47.      *   
  48.      * @return  
  49.      */  
  50.     Cache[] getCache();  
  51.   
  52. }  


[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package org.rui.utils;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutionException;  
  5. import java.util.concurrent.TimeUnit;  
  6.   
  7. import com.google.common.cache.Cache;  
  8. import com.google.common.cache.CacheBuilder;  
  9. import com.google.common.cache.CacheLoader;  
  10. import com.google.common.cache.LoadingCache;  
  11.   
  12. /**  
  13.  * 方便统一管理缓存 关于配置可根据系统实际情况配置  
  14.  *   
  15.  * @date 2015/6/7  
  16.  * @author liangrui  
  17.  *  
  18.  */  
  19. public class GuavaCachedImpl implements ICached<String, Object>  
  20. {  
  21.     /*** cached 缓存最大数量 **/  
  22.     public static final Integer CACHE_MAXIMUMSIZE = 10000;//  
  23.     /** loaderCached 缓存最大数量 **/  
  24.     public static final Integer LOADING_CACHE_MAXIMUMSIZE = 10000;  
  25.     /*** 缓存项在给定时间内没有被写访问(创建或覆盖),则回收 **/  
  26.     public static final Integer EXPIRE_AFTER_WRITE_MILLISECONDS = 1000;  
  27.   
  28.     private Cache<String, Object> cache = CacheBuilder  
  29.             .newBuilder()  
  30.             .maximumSize(CACHE_MAXIMUMSIZE)  
  31.             .expireAfterWrite(EXPIRE_AFTER_WRITE_MILLISECONDS,  
  32.                     TimeUnit.MILLISECONDS).recordStats().build();  
  33.   
  34.     private LoadingCache<String, Object> loadingCached = CacheBuilder  
  35.             .newBuilder()  
  36.             .maximumSize(LOADING_CACHE_MAXIMUMSIZE)  
  37.             .expireAfterWrite(EXPIRE_AFTER_WRITE_MILLISECONDS,  
  38.                     TimeUnit.MILLISECONDS)  
  39.             .build(new CacheLoader<String, Object>()  
  40.             {  
  41.                 @Override  
  42.                 public String load(String key) throws Exception  
  43.                 {  
  44.                     System.out.println("key:" + key);  
  45.                     if ("key".equals(key)) {  
  46.                         return "key return result";  
  47.                     } else {  
  48.                         return "get-if-absent-compute";  
  49.                     }  
  50.   
  51.                 }  
  52.   
  53.             });  
  54.   
  55.     @Override  
  56.     public Object getCallable(String key, Callable<Object> callable)  
  57.             throws ExecutionException  
  58.     {  
  59.         Object value = cache.get(key, callable);  
  60.         return value;  
  61.     }  
  62.   
  63.     @Override  
  64.     public Object getLoader(String key) throws ExecutionException  
  65.     {  
  66.         return loadingCached.get(key);  
  67.     }  
  68.   
  69.     @Override  
  70.     public Cache getCache(String cahced)  
  71.     {  
  72.         if ("cache".equals(cahced)) {  
  73.             return cache;  
  74.         }  
  75.         if ("loadingCached".equals(cahced)) {  
  76.             return loadingCached;  
  77.         } else {  
  78.   
  79.         }  
  80.         return null;  
  81.     }  
  82.   
  83.     @Override  
  84.     public Cache[] getCache()  
  85.     {  
  86.         Cache[] cacheArray = new Cache[]  
  87.         { cache, loadingCached };  
  88.   
  89.         return cacheArray;  
  90.     }  
  91.   
  92. }  

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package org.rui.utils;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.Map.Entry;  
  5. import java.util.Set;  
  6. import java.util.concurrent.Callable;  
  7. import java.util.concurrent.ExecutionException;  
  8.   
  9. import com.google.common.cache.Cache;  
  10. import com.google.common.cache.CacheStats;  
  11.   
  12. /**  
  13.  * cache 测试  
  14.  *   
  15.  * @author lenovo  
  16.  *  
  17.  */  
  18. public class Main  
  19. {  
  20.   
  21.     public static void main(String[] args) throws ExecutionException  
  22.     {  
  23.         ICached<String, Object> cached = new GuavaCachedImpl();  
  24.   
  25.         Object result = cached.getCallable("key1", new Callable<Object>()  
  26.         {  
  27.             @Override  
  28.             public Object call() throws Exception  
  29.             {  
  30.                 return "|cached value|";  
  31.             }  
  32.         });  
  33.   
  34.         System.out.println(cached.getLoader("key"));  
  35.         System.out.println(result);  
  36.   
  37.         printStats(cached.getCache());  
  38.   
  39.     }  
  40.   
  41.     /**  
  42.      * 打印缓存状态信息  
  43.      *   
  44.      * @param caches  
  45.      */  
  46.     public static void printStats(Cache[] caches)  
  47.     {  
  48.   
  49.         System.out.println("打印缓存状态信息");  
  50.         for (Cache cache : caches) {  
  51.             System.out.println();  
  52.             System.out  
  53.                     .println("start------------------------------------------> ");  
  54.             System.out.println("loadCount:" + cache.stats().loadCount()  
  55.                     + "  loadSsuccessCount: "  
  56.                     + cache.stats().loadSuccessCount());  
  57.   
  58.             System.out.println("缓存命中率:" + cache.stats().hitRate()  
  59.                     + " hitCount: " + cache.stats().hitCount());// 缓存命中率;  
  60.             System.out.println("加载新值的平均时间:"  
  61.                     + cache.stats().averageLoadPenalty() + " 纳秒");// 加载新值的平均时间,单位为纳秒;  
  62.             System.out.println("缓存项被回收的总数:" + cache.stats().evictionCount());// 缓存项被回收的总数,不包括显式清除。  
  63.             System.out.println();  
  64.   
  65.             System.out.println();  
  66.             System.out.println("cached 健和值 ===============");  
  67.   
  68.             Set setEn = cache.asMap().entrySet();  
  69.             Iterator<Object> it = setEn.iterator();  
  70.             System.out.println();  
  71.             System.out.println("all entrySet====>");  
  72.             while (it.hasNext()) {  
  73.                 System.out.print(it.next() + " \t ");  
  74.             }  
  75.   
  76.             System.out.println();  
  77.             System.out.println();  
  78.             Set<String> set = cache.asMap().keySet();// 所有健  
  79.             Iterator<String> it2 = set.iterator();  
  80.             System.out.println("all key====>");  
  81.             while (it2.hasNext()) {  
  82.                 System.out.print(it2.next() + " \t ");  
  83.             }  
  84.             System.out.println();  
  85.             System.out  
  86.                     .println("end------------------------------------------> ");  
  87.         }  
  88.     }  
  89.   
  90. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值