1、开头
有些数据需要去网络上加载,但不能每次都加载,所以这次一般会缓存到本地。缓存到本地的介质有很多。可以使文件,或者本地数据库。我们这次的是缓存到内存。
2、使用对象缓存,即可以缓存对象。
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,因为缓存过期了,需要重新加载。
3、bitmap缓存使用。如果要缓存的是bitmap图片,虽然也能用上面的对象缓存。但是最好用下面专门为bitmap定制的缓存。
Cache<String, Object> cache = AnCacheUtils.getBitmapMemoryCache();
cache.put("anan", bitmap);
...
Bitmap cacheBitmap = cache.get("anan");
这默认bitmap缓存大小3M。想必你也想到了吧,为什么要把bitmap缓存和对象缓存分开。对象内存容量不好统计,所以用个来计算。而bitmap的特殊性,如果用个数来限制,很容易出现OOM。所以用他的占用内存来做限制。
4、刷新缓存和关闭缓存
Cache<String, Object> cache = AnCacheUtils.getObjectMemoryCache();
cache.removeAll();
...想要关闭默认缓存可以如下
AnCacheUtils.closeObjectCache();
5、我们还可以自定义设置默认缓存限制。以对象缓存为例子。
AnCacheUtils.configObjectCacheSize(30);
Cache<String, Object> cache = AnCacheUtils.getObjectMemoryCache();
要注意的是,一旦从新限制缓存限制。那么之前的缓存都会清空。这种操作最好在程序初始化的时候设置,然后之后就保持不变了。
6、总结
其实这个缓存用法还是比较简单的,可以看成一个map,缓存的时候put一下,要用缓存的时候get一下,就可以了。
源码在github上有:https://github.com/bigapple520520/bigapple