一、开头 java
有些数据须要去网络上加载,但不能每次都加载,因此此次通常会缓存到本地。缓存到本地的介质有不少。能够使文件,或者本地数据库。咱们此次的是缓存到内存。 git
二、使用对象缓存,便可以缓存对象。 github
Cache<String, Object> cache = AnCacheUtils.getObjectMemoryCache(); cache.put("xuan", "你好,我被缓存了");
上面就是缓存了一个字符串。AnCacheUtils.getObjectMemoryCache()取到的是一个默认的缓存对象。最大限制默认20个。使用LRU缓存算法。 算法
取缓存就更简单了。以下: 数据库
Cache<String, Object> cache = AnCacheUtils.getObjectMemoryCache(); String cacheStr = (String)cache.get("xuan");cacheStr取到的就是最初存放的那个串。固然,咱们还复写了一个put方法,用来支持缓存过时。使用以下:
Cache<String, Object> cache = AnCacheUtils.getObjectMemoryCache(); Date currentTime = new Date(); cache.put("xuan", "你好", currentTime.getTime() + 2000);// 过时2S ...中间让时间超过2S String cacheStr = (String)cache.get("xuan");如你所想,这里的cacheStr取到的是null,由于缓存过时了,须要从新加载。
三、bitmap缓存使用。若是要缓存的是bitmap图片,虽然也能用上面的对象缓存。可是最好用下面专门为bitmap定制的缓存。 缓存
Cache<String, Object> cache = AnCacheUtils.getBitmapMemoryCache(); cache.put("anan", bitmap); ... Bitmap cacheBitmap = cache.get("anan");这默认bitmap缓存大小3M。想必你也想到了吧,为何要把bitmap缓存和对象缓存分开。对象内存容量很差统计,因此用个来计算。而bitmap的特殊性,若是用个数来限制,很容易出现OOM。因此用他的占用内存来作限制。
四、刷新缓存和关闭缓存 网络
Cache<String, Object> cache = AnCacheUtils.getObjectMemoryCache(); cache.removeAll(); ...想要关闭默认缓存能够以下 AnCacheUtils.closeObjectCache();
五、咱们还能够自定义设置默认缓存限制。以对象缓存为例子。 app
AnCacheUtils.configObjectCacheSize(30); Cache<String, Object> cache = AnCacheUtils.getObjectMemoryCache();要注意的是,一旦重新限制缓存限制。那么以前的缓存都会清空。这种操做最好在程序初始化的时候设置,而后以后就保持不变了。
六、总结 spa
其实这个缓存用法仍是比较简单的,能够当作一个map,缓存的时候put一下,要用缓存的时候get一下,就能够了。 code
源码在github上有:https://github.com/bigapple520520/bigapple