Android 的二级缓存如斯简单

4,602 阅读2分钟

CacheDiskUtils

之前写过一篇 你想要的 CacheUtils,简单介绍了下其可以完美替代 ASimpleCache,而且修复了其中少许 BUG 并做了相应优化,相关 API 如下所示:

缓存相关 -> CacheUtils.java

getInstance             : 获取缓存实例
Instance.put            : 缓存中写入数据
Instance.getBytes       : 缓存中读取字节数组
Instance.getString      : 缓存中读取 String
Instance.getJSONObject  : 缓存中读取 JSONObject
Instance.getJSONArray   : 缓存中读取 JSONArray
Instance.getBitmap      : 缓存中读取 Bitmap
Instance.getDrawable    : 缓存中读取 Drawable
Instance.getParcelable  : 缓存中读取 Parcelable
Instance.getSerializable: 缓存中读取 Serializable
Instance.getCacheSize   : 获取缓存大小
Instance.getCacheCount  : 获取缓存个数
Instance.remove         : 根据键值移除缓存
Instance.clear          : 清除所有缓存

其也就是所谓的硬盘缓存,在 AndroidUtilCode 1.17.0 版本,该 CacheUtils 已被我标记废弃,可替换为 CacheDiskUtils,下一个大版本1.18.x 可能就会移除 CacheUtils

CacheMemoryUtils

讲了磁盘缓存另一个就是内存缓存,内存缓存工具类 CacheMemoryUtils 原理是利用 LruCache 来实现的(LRU 是Least Recently Used的缩写,即最近最少使用),其 API 如下所示:

内存缓存相关 -> CacheMemoryUtils.java -> Test

getInstance           : 获取缓存实例
Instance.put          : 缓存中写入数据
Instance.get          : 缓存中读取字节数组
Instance.getCacheCount: 获取缓存个数
Instance.remove       : 根据键值移除缓存
Instance.clear        : 清除所有缓存

CacheDoubleUtils

结合硬盘缓存工具类 CacheDiskUtils 和内存缓存工具类 CacheMemoryUtils,那么我们的二级缓存工具类 CacheDoubleUtils 便诞生了,其 API 如下所示:

二级缓存相关 -> CacheDoubleUtils.java -> Test

getInstance                 : 获取缓存实例
Instance.put                : 缓存中写入数据
Instance.getBytes           : 缓存中读取字节数组
Instance.getString          : 缓存中读取 String
Instance.getJSONObject      : 缓存中读取 JSONObject
Instance.getJSONArray       : 缓存中读取 JSONArray
Instance.getBitmap          : 缓存中读取 Bitmap
Instance.getDrawable        : 缓存中读取 Drawable
Instance.getParcelable      : 缓存中读取 Parcelable
Instance.getSerializable    : 缓存中读取 Serializable
Instance.getCacheDiskSize   : 获取磁盘缓存大小
Instance.getCacheDiskCount  : 获取磁盘缓存个数
Instance.getCacheMemoryCount: 获取内存缓存个数
Instance.remove             : 根据键值移除缓存
Instance.clear              : 清除所有缓存

借助以上三个缓存工具类,那么 Android 端的缓存实现便再也不是什么难题了,例如你想要实现 RxCache,那么借助 RxJava 的 compose 操作符和我的工具类,把数据放入缓存不就轻而易举地实现了么,更多风骚的姿势可待你解锁。

文章比较简短精细,但实现的代码是比较漫长粗壮的,要阅读源码和单测可以 fork 我的 AndroidUtilCode 来查看,相信你会懂得我为这个工具类的付出。