guava cache使用简介

  概述

  缓存是日常开发中经常应用到的一种技术手段,合理的利用缓存可以极大的改善应用程序的性能。
  Guava官方对Cache的描述连接
  缓存在各种各样的用例中非常有用。例如,当计算或检索值很昂贵时,您应该考虑使用缓存,并且不止一次需要它在某个输入上的值。
  缓存ConcurrentMap要小,但不完全相同。最根本的区别在于一个ConcurrentMap坚持所有添加到它直到他们明确地删除元素。
  另一方面,缓存一般配置为自动退出的条目,以限制其内存占用。在某些情况下,一个LoadingCache可以即使不驱逐的条目是有用的,因为它的自动缓存加载。

  适用性
  你愿意花一些内存来提高速度。You are willing to spend some memory to improve speed.
  您希望Key有时会不止一次被查询。You expect that keys will sometimes get queried more than once.
  你的缓存不需要存储更多的数据比什么都适合在。(Guava缓存是本地应用程序的一次运行)。Your cache will not need to store more data than what would fit inRAM. (Guava caches are local to a single run of your application.
  它们不将数据存储在文件中,也不存储在外部服务器上。如果这样做不适合您的需要,考虑一个工具像memcached。

  

  基于引用的回收(Reference-based Eviction)强(strong)、软(soft)、弱(weak)、虚(phantom)引用-参考
  通过使用弱引用的键、或弱引用的值、或软引用的值,Guava Cache可以把缓存设置为允许垃圾回收:
  CacheBuilder.weakKeys():使用弱引用存储键。当键没有其它(强或软)引用时,缓存项可以被垃圾回收。因为垃圾回收仅依赖恒等式(==),使用弱引用键的缓存用==而不是equals比较键。
  CacheBuilder.weakValues():使用弱引用存储值。当值没有其它(强或软)引用时,缓存项可以被垃圾回收。因为垃圾回收仅依赖恒等式(==),使用弱引用值的缓存用==而不是equals比较值。
  CacheBuilder.softValues():使用软引用存储值。软引用只有在响应内存需要时,才按照全局最近最少使用的顺序回收。考虑到使用软引用的性能影响,我们通常建议使用更有性能预测性的缓存大小限定(见上文,基于容量回收)。使用软引用值的缓存同样用==而不是equals比较值。!

  guava cache 是利用CacheBuilder类用builder模式构造出两种不同的cache加载方式CacheLoader,Callable,共同逻辑都是根据key是加载value。不同的地方在于CacheLoader的定义比较宽泛,是针对整个cache定义的,可以认为是统一的根据key值load value的方法,而Callable的方式较为灵活,允许你在get的时候指定load方法。看以下代码

 1         Cache<String,Object> cache = CacheBuilder.newBuilder()
 2                 .expireAfterWrite(10, TimeUnit.SECONDS).maximumSize(500).build();
 3  
 4          cache.get("key", new Callable<Object>() { //Callable 加载
 5             @Override
 6             public Object call() throws Exception {
 7                 return "value";
 8             }
 9         });
10  
11         LoadingCache<String, Object> loadingCache = CacheBuilder.newBuilder()
12                 .expireAfterAccess(30, TimeUnit.SECONDS).maximumSize(5)
13                 .build(new CacheLoader<String, Object>() {
14                     @Override
15                     public Object load(String key) throws Exception {
16                         return "value";
17                     }
18                 });    

 

 guava Cache数据移除:

  guava做cache时候数据的移除方式,在guava中数据的移除分为被动移除和主动移除两种。
  被动移除数据的方式,guava默认提供了三种方式:
  1.基于大小的移除:看字面意思就知道就是按照缓存的大小来移除,如果即将到达指定的大小,那就会把不常用的键值对从cache中移除。
  定义的方式一般为 CacheBuilder.maximumSize(long),还有一种一种可以算权重的方法,个人认为实际使用中不太用到。就这个常用的来看有几个注意点,
    其一,这个size指的是cache中的条目数,不是内存大小或是其他;
    其二,并不是完全到了指定的size系统才开始移除不常用的数据的,而是接近这个size的时候系统就会开始做移除的动作;
    其三,如果一个键值对已经从缓存中被移除了,你再次请求访问的时候,如果cachebuild是使用cacheloader方式的,那依然还是会从cacheloader中再取一次值,如果这样还没有,就会抛出异常
  2.基于时间的移除:guava提供了两个基于时间移除的方法
    expireAfterAccess(long, TimeUnit)  这个方法是根据某个键值对最后一次访问之后多少时间后移除
    expireAfterWrite(long, TimeUnit)  这个方法是根据某个键值对被创建或值被替换后多少时间移除
  3.基于引用的移除:
  这种移除方式主要是基于java的垃圾回收机制,根据键或者值的引用关系决定移除
  主动移除数据方式,主动移除有三种方法
  1.单独移除用 Cache.invalidate(key)
  2.批量移除用 Cache.invalidateAll(keys)
  3.移除所有用 Cache.invalidateAll()
  如果需要在移除数据的时候有所动作还可以定义Removal Listener,但是有点需要注意的是默认Removal Listener中的行为是和移除动作同步执行的,如果需要改成异步形式,可以考虑使用RemovalListeners.asynchronous(RemovalListener, Executor)

  现在来实战演示:

  1.maven依赖 

1 <dependency>
2    <groupId>com.google.guava</groupId>
3    <artifactId>guava</artifactId>
4    <version>23.0</version>
5 </dependency>

  2.GuavaAbstractLoadingCache  缓存加载方式和基本属性使用基类(我用的是CacheBuilder)

  1 import com.google.common.cache.CacheBuilder;
  2 import com.google.common.cache.CacheLoader;
  3 import com.google.common.cache.LoadingCache;
  4 import org.slf4j.Logger;
  5 import org.slf4j.LoggerFactory;
  6 
  7 import java.util.Date;
  8 import java.util.concurrent.ExecutionException;
  9 import java.util.concurrent.TimeUnit;
 10 
 11 /**
 12  * @ClassName: GuavaAbstractLoadingCache
 13  * @author LiJing
 14  * @date 2018/11/2 11:09 
 15  *
 16  */
 17 
 18 public abstract class GuavaAbstractLoadingCache <K, V> {
 19     protected final Logger logger = LoggerFactory.getLogger(this.getClass());
 20 
 21     //用于初始化cache的参数及其缺省值
 22     private int maximumSize = 1000;                 //最大缓存条数,子类在构造方法中调用setMaximumSize(int size)来更改
 23     private int expireAfterWriteDuration = 60;      //数据存在时长,子类在构造方法中调用setExpireAfterWriteDuration(int duration)来更改
 24     private TimeUnit timeUnit = TimeUnit.MINUTES;   //时间单位(分钟)
 25 
 26     private Date resetTime;     //Cache初始化或被重置的时间
 27     private long highestSize=0; //历史最高记录数
 28     private Date highestTime;   //创造历史记录的时间
 29 
 30     private LoadingCache<K, V> cache;
 31 
 32     /**
 33      * 通过调用getCache().get(key)来获取数据
 34      * @return cache
 35      */
 36     public LoadingCache<K, V> getCache() {
 37         if(cache == null){  //使用双重校验锁保证只有一个cache实例
 38             synchronized (this) {
 39                 if(cache == null){
 40                     cache = CacheBuilder.newBuilder().maximumSize(maximumSize)      //缓存数据的最大条目,也可以使用.maximumWeight(weight)代替
 41                             .expireAfterWrite(expireAfterWriteDuration, timeUnit)   //数据被创建多久后被移除
 42                             .recordStats()                                          //启用统计
 43                             .build(new CacheLoader<K, V>() {
 44                                 @Override
 45                                 public V load(K key) throws Exception {
 46                                     return fetchData(key);
 47                                 }
 48                             });
 49                     this.resetTime = new Date();
 50                     this.highestTime = new Date();
 51                     logger.debug("本地缓存{}初始化成功", this.getClass().getSimpleName());
 52                 }
 53             }
 54         }
 55 
 56         return cache;
 57     }
 58 
 59     /**
 60      * 根据key从数据库或其他数据源中获取一个value,并被自动保存到缓存中。
 61      * @param key
 62      * @return value,连同key一起被加载到缓存中的。
 63      */
 64     protected abstract V fetchData(K key) throws Exception;
 65 
 66     /**
 67      * 从缓存中获取数据(第一次自动调用fetchData从外部获取数据),并处理异常
 68      * @param key
 69      * @return Value
 70      * @throws ExecutionException
 71      */
 72     protected V getValue(K key) throws ExecutionException {
 73         V result = getCache().get(key);
 74         if(getCache().size() > highestSize){
 75             highestSize = getCache().size();
 76             highestTime = new Date();
 77         }
 78 
 79         return result;
 80     }
 81 
 82     public long getHighestSize() {
 83         return highestSize;
 84     }
 85 
 86     public Date getHighestTime() {
 87         return highestTime;
 88     }
 89 
 90     public Date getResetTime() {
 91         return resetTime;
 92     }
 93 
 94     public void setResetTime(Date resetTime) {
 95         this.resetTime = resetTime;
 96     }
 97 
 98     public int getMaximumSize() {
 99         return maximumSize;
100     }
101 
102     public int getExpireAfterWriteDuration() {
103         return expireAfterWriteDuration;
104     }
105 
106     public TimeUnit getTimeUnit() {
107         return timeUnit;
108     }
109 
110     /**
111      * 设置最大缓存条数
112      * @param maximumSize
113      */
114     public void setMaximumSize(int maximumSize) {
115         this.maximumSize = maximumSize;
116     }
117 
118     /**
119      * 设置数据存在时长(分钟)
120      * @param expireAfterWriteDuration
121      */
122     public void setExpireAfterWriteDuration(int expireAfterWriteDuration) {
123         this.expireAfterWriteDuration = expireAfterWriteDuration;
124     }
125 }

 

   3.ILocalCache 缓存获取调用接口 (用接口方式 类业务操作)

1 public interface ILocalCache <K, V> {
2 
3     /**
4      * 从缓存中获取数据
5      * @param key
6      * @return value
7      */
8     public V get(K key);
9 }

   4.缓存获取的实现方法 缓存实例

 1 import com.cn.alasga.merchant.bean.area.Area;
 2 import com.cn.alasga.merchant.mapper.area.AreaMapper;
 3 import com.cn.alasga.merchant.service.area.AreaService;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.stereotype.Component;
 6 
 7 
 8 /**
 9  * @author LiJing
10  * @ClassName: LCAreaIdToArea
11  * @date 2018/11/2 11:12
12  */
13 
14 @Component
15 public class AreaCache extends GuavaAbstractLoadingCache<Long, Area> implements ILocalCache<Long, Area> {
16 
17     @Autowired
18     private AreaService areaService;
19 
20     //由Spring来维持单例模式
21     private AreaCache() {
22         setMaximumSize(4000); //最大缓存条数
23     }
24 
25     @Override
26     public Area get(Long key) {
27         try {
28             Area value = getValue(key);
29             return value;
30         } catch (Exception e) {
31             logger.error("无法根据baseDataKey={}获取Area,可能是数据库中无该记录。", key, e);
32             return null;
33         }
34     }
35 
36     /**
37      * 从数据库中获取数据
38      */
39     @Override
40     protected Area fetchData(Long key) {
41         logger.debug("测试:正在从数据库中获取area,area id={}", key);
42         return areaService.getAreaInfo(key);
43     }
44 }

  至此,以上就完成了,简单缓存搭建,就可以使用了. 其原理就是就是先从缓存中查询,没有就去数据库中查询放入缓存,再去维护缓存,基于你设置的属性,只需集成缓存实现接口就可以扩展缓存了............上面就是举个栗子

   4.再来编写缓存管理,进行缓存的管理  这里是统一的缓存管理 可以返回到Controller去统一管理

  1 import com.cn.alasga.common.core.page.PageParams;
  2 import com.cn.alasga.common.core.page.PageResult;
  3 import com.cn.alasga.common.core.util.SpringContextUtil;
  4 import com.google.common.cache.CacheStats;
  5 
  6 import java.text.NumberFormat;
  7 import java.text.SimpleDateFormat;
  8 import java.time.LocalDateTime;
  9 import java.time.ZoneId;
 10 import java.util.*;
 11 import java.util.concurrent.ConcurrentMap;
 12 
 13 /**
 14  * @ClassName: GuavaCacheManager
 15  * @author LiJing
 16  * @date 2018/11/2 11:17 
 17  *
 18  */
 19 public class GuavaCacheManager {
 20 
 21     //保存一个Map: cacheName -> cache Object,以便根据cacheName获取Guava cache对象
 22     private static Map<String, ? extends GuavaAbstractLoadingCache<Object, Object>> cacheNameToObjectMap = null;
 23 
 24     /**
 25      * 获取所有GuavaAbstractLoadingCache子类的实例,即所有的Guava Cache对象
 26      * @return
 27      */
 28 
 29     @SuppressWarnings("unchecked")
 30     private static Map<String, ? extends GuavaAbstractLoadingCache<Object, Object>> getCacheMap(){
 31         if(cacheNameToObjectMap==null){
 32             cacheNameToObjectMap = (Map<String, ? extends GuavaAbstractLoadingCache<Object, Object>>) SpringContextUtil.getBeanOfType(GuavaAbstractLoadingCache.class);
 33         }
 34         return cacheNameToObjectMap;
 35 
 36     }
 37 
 38     /**
 39      *  根据cacheName获取cache对象
 40      * @param cacheName
 41      * @return
 42      */
 43     private static GuavaAbstractLoadingCache<Object, Object> getCacheByName(String cacheName){
 44         return (GuavaAbstractLoadingCache<Object, Object>) getCacheMap().get(cacheName);
 45     }
 46 
 47     /**
 48      * 获取所有缓存的名字(即缓存实现类的名称)
 49      * @return
 50      */
 51     public static Set<String> getCacheNames() {
 52         return getCacheMap().keySet();
 53     }
 54 
 55     /**
 56      * 返回所有缓存的统计数据
 57      * @return List<Map<统计指标,统计数据>>
 58      */
 59     public static ArrayList<Map<String, Object>> getAllCacheStats() {
 60 
 61         Map<String, ? extends Object> cacheMap = getCacheMap();
 62         List<String> cacheNameList = new ArrayList<>(cacheMap.keySet());
 63         Collections.sort(cacheNameList);//按照字母排序
 64 
 65         //遍历所有缓存,获取统计数据
 66         ArrayList<Map<String, Object>> list = new ArrayList<>();
 67         for(String cacheName : cacheNameList){
 68             list.add(getCacheStatsToMap(cacheName));
 69         }
 70 
 71         return list;
 72     }
 73 
 74     /**
 75      * 返回一个缓存的统计数据
 76      * @param cacheName
 77      * @return Map<统计指标,统计数据>
 78      */
 79     private static Map<String, Object> getCacheStatsToMap(String cacheName) {
 80         Map<String, Object> map =  new LinkedHashMap<>();
 81         GuavaAbstractLoadingCache<Object, Object> cache = getCacheByName(cacheName);
 82         CacheStats cs = cache.getCache().stats();
 83         NumberFormat percent = NumberFormat.getPercentInstance(); // 建立百分比格式化用
 84         percent.setMaximumFractionDigits(1); // 百分比小数点后的位数
 85         map.put("cacheName", cacheName);//Cache名称
 86         map.put("size", cache.getCache().size());//当前数据量
 87         map.put("maximumSize", cache.getMaximumSize());//最大缓存条数
 88         map.put("survivalDuration", cache.getExpireAfterWriteDuration());//过期时间
 89         map.put("hitCount", cs.hitCount());//命中次数
 90         map.put("hitRate", percent.format(cs.hitRate()));//命中比例
 91         map.put("missRate", percent.format(cs.missRate()));//读库比例
 92         map.put("loadSuccessCount", cs.loadSuccessCount());//成功加载数
 93         map.put("loadExceptionCount", cs.loadExceptionCount());//成功加载数
 94         map.put("totalLoadTime", cs.totalLoadTime()/1000000);       //总加载毫秒ms
 95         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 96         if(cache.getResetTime()!=null){
 97             map.put("resetTime", df.format(cache.getResetTime()));//重置时间
 98             LocalDateTime localDateTime = LocalDateTime.ofInstant(cache.getResetTime().toInstant(), ZoneId.systemDefault()).plusMinutes(cache.getTimeUnit().toMinutes(cache.getExpireAfterWriteDuration()));
 99             map.put("survivalTime", df.format(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant())));//失效时间
100         }
101         map.put("highestSize", cache.getHighestSize());//历史最高数据量
102         if(cache.getHighestTime()!=null){
103             map.put("highestTime", df.format(cache.getHighestTime()));//最高数据量时间
104         }
105 
106         return map;
107     }
108 
109     /**
110      * 根据cacheName清空缓存数据
111      * @param cacheName
112      */
113     public static void resetCache(String cacheName){
114         GuavaAbstractLoadingCache<Object, Object> cache = getCacheByName(cacheName);
115         cache.getCache().invalidateAll();
116         cache.setResetTime(new Date());
117     }
118 
119     /**
120      * 分页获得缓存中的数据
121      * @param pageParams
122      * @return
123      */
124     public static PageResult<Object> queryDataByPage(PageParams<Object> pageParams) {
125         PageResult<Object> data = new PageResult<>(pageParams);
126 
127         GuavaAbstractLoadingCache<Object, Object> cache = getCacheByName((String) pageParams.getParams().get("cacheName"));
128         ConcurrentMap<Object, Object> cacheMap = cache.getCache().asMap();
129         data.setTotalRecord(cacheMap.size());
130         data.setTotalPage((cacheMap.size()-1)/pageParams.getPageSize()+1);
131 
132         //遍历
133         Iterator<Map.Entry<Object, Object>> entries = cacheMap.entrySet().iterator();
134         int startPos = pageParams.getStartPos()-1;
135         int endPos = pageParams.getEndPos()-1;
136         int i=0;
137         Map<Object, Object> resultMap = new LinkedHashMap<>();
138         while (entries.hasNext()) {
139             Map.Entry<Object, Object> entry = entries.next();
140             if(i>endPos){
141                 break;
142             }
143 
144             if(i>=startPos){
145                 resultMap.put(entry.getKey(), entry.getValue());
146             }
147 
148             i++;
149         }
150         List<Object> resultList = new ArrayList<>();
151         resultList.add(resultMap);
152         data.setResults(resultList);
153         return data;
154     }
155 }

  缓存service

 1 import com.alibaba.dubbo.config.annotation.Service;
 2 import com.cn.alasga.merchant.cache.GuavaCacheManager;
 3 import com.cn.alasga.merchant.service.cache.CacheService;
 4 
 5 import java.util.ArrayList;
 6 import java.util.Map;
 7 
 8 /**
 9  * @ClassName: CacheServiceImpl
10  * @author zhoujl
11  * @date 2018.11.6 下午 5:29
12  *
13  */
14 @Service(version = "1.0.0")
15 public class CacheServiceImpl implements CacheService {
16 
17     @Override
18     public ArrayList<Map<String, Object>> getAllCacheStats() {
19         return GuavaCacheManager.getAllCacheStats();
20     }
21 
22     @Override
23     public void resetCache(String cacheName) {
24         GuavaCacheManager.resetCache(cacheName);
25     }
26 }

  缓存控制器

  1 import com.alibaba.dubbo.config.annotation.Reference;
  2 import com.cn.alasga.common.core.page.JsonResult;
  3 import com.cn.alasga.merchant.service.cache.CacheService;
  4 import com.github.pagehelper.PageInfo;
  5 import org.apache.shiro.authz.annotation.RequiresPermissions;
  6 import org.springframework.stereotype.Controller;
  7 import org.springframework.web.bind.annotation.*;
  8 
  9 /**
 10  * @ClassName: CacheAdminController
 11  * @author LiJing
 12  * @date 2018/11/6 10:10 
 13  *
 14  */
 15 @Controller
 16 @RequestMapping("/cache")
 17 public class CacheAdminController {
 18 
 19     @Reference(version = "1.0.0")
 20     private CacheService cacheService;
 21 
 22     @GetMapping("")
 23     @RequiresPermissions("cache:view")
 24     public String index() {
 25         return "admin/system/cache/cacheList";
 26     }
 27 
 28     @PostMapping("/findPage")
 29     @ResponseBody
 30     @RequiresPermissions("cache:view")
 31     public PageInfo findPage() {
 32         return new PageInfo<>(cacheService.getAllCacheStats());
 33     }
 34 
 35     /**
 36      * 清空缓存数据、并返回清空后的统计信息
 37      * @param cacheName
 38      * @return
 39      */
 40     @RequestMapping(value = "/reset", method = RequestMethod.POST)
 41     @ResponseBody
 42     @RequiresPermissions("cache:reset")
 43     public JsonResult cacheReset(String cacheName) {
 44         JsonResult jsonResult = new JsonResult();
 45 
 46         cacheService.resetCache(cacheName);
 47         jsonResult.setMessage("已经成功重置了" + cacheName + "!");
 48 
 49         return jsonResult;
 50     }
 51 
 52     /**
 53      * 查询cache统计信息
 54      * @param cacheName
 55      * @return cache统计信息
 56      */
 57     /*@RequestMapping(value = "/stats", method = RequestMethod.POST)
 58     @ResponseBody
 59     public JsonResult cacheStats(String cacheName) {
 60         JsonResult jsonResult = new JsonResult();
 61 
 62         //暂时只支持获取全部
 63 
 64         switch (cacheName) {
 65             case "*":
 66                 jsonResult.setData(GuavaCacheManager.getAllCacheStats());
 67                 jsonResult.setMessage("成功获取了所有的cache!");
 68                 break;
 69 
 70             default:
 71                 break;
 72         }
 73 
 74         return jsonResult;
 75     }*/
 76 
 77     /**
 78      * 返回所有的本地缓存统计信息
 79      * @return
 80      */
 81     /*@RequestMapping(value = "/stats/all", method = RequestMethod.POST)
 82     @ResponseBody
 83     public JsonResult cacheStatsAll() {
 84         return cacheStats("*");
 85     }*/
 86 
 87     /**
 88      * 分页查询数据详情
 89      * @param params
 90      * @return
 91      */
 92     /*@RequestMapping(value = "/queryDataByPage", method = RequestMethod.POST)
 93     @ResponseBody
 94     public PageResult<Object> queryDataByPage(@RequestParam Map<String, String> params){
 95         int pageSize = Integer.valueOf(params.get("pageSize"));
 96         int pageNo = Integer.valueOf(params.get("pageNo"));
 97         String cacheName = params.get("cacheName");
 98 
 99         PageParams<Object> page = new PageParams<>();
100         page.setPageSize(pageSize);
101         page.setPageNo(pageNo);
102         Map<String, Object> param = new HashMap<>();
103         param.put("cacheName", cacheName);
104         page.setParams(param);
105 
106         return GuavaCacheManager.queryDataByPage(page);
107     }*/
108 }

  以上就是gauva缓存,可以reset每一个缓存,管理每一个缓存,更新一些不经常改变的数据.   下面是页面展示~~~~~~~~~~

 

  

posted on 2018-12-18 11:26  锦成同学  阅读(2958)  评论(1编辑  收藏  举报