JsonCacheUtil-缓存工具类

/**
 * Project_name:TaobaoUnion
 * Created by:ChenFuXu.
 * Date: 2022/3/20 20:07
 *
 * 缓存工具类
 */
public class JsonCacheUtil {
    public static final String JSON_CACHE_SP_NAME = "json_cache_sp_name";
    private static volatile JsonCacheUtil sJsonCacheUtil = null;
    private final SharedPreferences mSharedPreferences;
    private final Gson mGson;

    private JsonCacheUtil() {
        mSharedPreferences = BaseApplication.getAppContext().getSharedPreferences(JSON_CACHE_SP_NAME
                , Context.MODE_PRIVATE);
        mGson = new Gson();
    }

    public static JsonCacheUtil getInstance() {
        if (sJsonCacheUtil == null) {
            synchronized (JsonCacheUtil.class) {
                if (sJsonCacheUtil == null) {
                    sJsonCacheUtil = new JsonCacheUtil();
                }
            }
        }
        return sJsonCacheUtil;
    }

    // 增加数据
    public void saveCache(String key, Object value) {
        this.saveCache(key, value, -1);
    }

    /**
     *
     * @param key
     * @param value
     * @param duration 表示设置的缓存的时间
     */
    public void saveCache(String key, Object value, long duration) {
        SharedPreferences.Editor edit = mSharedPreferences.edit();
        // 将对象转成字符串
        String valueStr = mGson.toJson(value);
        if (duration != -1L) {
            /**
             * 比如设置的缓存的时间为100s,那么100s后过期
             * 这里加上当前的系统时间
             */
            duration += System.currentTimeMillis();
        }
        CacheDuration cacheDuration = new CacheDuration(duration, valueStr);
        String cacheDurationStr = mGson.toJson(cacheDuration); // 转成字符串
        edit.putString(key, cacheDurationStr);
        edit.apply();
    }

    // 删除数据
    public void delCache(String key) {
        mSharedPreferences.edit().remove(key).apply();
    }

    // 获取数据
    public <T extends Class> T  getValue(String key, Class<T> clazz) {
        String valueWithDuration = mSharedPreferences.getString(key, null);
        if (valueWithDuration == null) {
            return null;
        }
        CacheDuration cacheDuration = mGson.fromJson(valueWithDuration, CacheDuration.class);
        long duration = cacheDuration.getDuration();
        // 此处减去当前的系统时间,如果大于0,表示未超时,小于0,表示缓存时间已到
        if (duration != -1L && (duration - System.currentTimeMillis()) < 0) {
            // 过期了
            return null;
        } else {
            // 未过期
            // 获取缓存的内容字符串
            String cacheStr = cacheDuration.getCache();
            // 转为对象
            return mGson.fromJson(cacheStr, clazz);
        }
    }
}

可以用来缓存对象,duration为设置需要缓存的时间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值