Cache 工具类

March 16, 2025 · View on GitHub

使用演示类 CacheUse 介绍了配置参数及使用

项目类结构 - 包目录

  • 缓存工具类(DevCache):缓存工具类,提供各种保存数据方法

  • 缓存管理类(DevCacheManager):内部缓存管理类

API 文档

方法注释
newCache获取 DevCache
getCachePath获取缓存地址
remove移除数据
removeForKeys删除 Key[] 配置、数据文件
contains是否存在 key
isDue判断某个 key 是否过期
clear清除全部数据
clearDue清除过期数据
clearType清除某个类型的全部数据
getItemByKey通过 Key 获取 Item
getKeys获取有效 Key 集合
getPermanentKeys获取永久有效 Key 集合
getCount获取有效 Key 数量
getSize获取有效 Key 占用总大小
put保存 int 类型的数据
getInt获取 int 类型的数据
getLong获取 long 类型的数据
getFloat获取 float 类型的数据
getDouble获取 double 类型的数据
getBoolean获取 boolean 类型的数据
getString获取 String 类型的数据
getBytes获取 byte[] 类型的数据
getBitmap获取 Bitmap 类型的数据
getDrawable获取 Drawable 类型的数据
getSerializable获取 Serializable 类型的数据
getParcelable获取 Parcelable 类型的数据
getJSONObject获取 JSONObject 类型的数据
getJSONArray获取 JSONArray 类型的数据
getKey获取存储 Key
isPermanent是否永久有效
getType获取数据存储类型
getSaveTime获取保存时间 ( 毫秒 )
getValidTime获取有效期 ( 毫秒 )
setTypesetType
setSaveTimesetSaveTime
setValidTimesetValidTime
isIntisInt
isLongisLong
isFloatisFloat
isDoubleisDouble
isBooleanisBoolean
isStringisString
isBytesisBytes
isBitmapisBitmap
isDrawableisDrawable
isSerializableisSerializable
isParcelableisParcelable
isJSONObjectisJSONObject
isJSONArrayisJSONArray

使用示例

// 初始化
CacheVo cacheVo = new CacheVo("测试持久化");
// 打印信息
DevEngine.getLog().dTag(TAG, "保存前: %s", cacheVo.toString());
// 保存数据
DevCache.newCache().put("ctv", cacheVo, -1);
// 重新获取
CacheVo ctv = (CacheVo) DevCache.newCache().getSerializable("ctv");
// 打印获取后的数据
DevEngine.getLog().dTag(TAG, "保存后: %s", ctv.toString());
// 设置保存有效时间 5秒
DevCache.newCache().put("ctva", new CacheVo("测试有效时间"), 1);

// 保存到指定文件夹下
DevCache.newCache(
        new File(PathUtils.getSDCard().getSDCardPath(), "Cache").getAbsolutePath()
).put("key", "保存数据", -1);

// 延迟后
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            // 延迟 1.5 已经过期再去获取
            Thread.sleep(1500);
            // 获取数据
            CacheVo ctva = (CacheVo) DevCache.newCache().getSerializable("ctva");
            // 判断是否过期
            DevEngine.getLog().dTag(TAG, "是否过期: %s", (ctva == null));
        } catch (Exception ignored) {
        }
    }
}).start();