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
    评论
Caffeine是一款高性能、最优缓存库,受到了Google Guava缓存和ConcurrentLinkedHashMap的启发而设计。它提供了多种加载方式,包括手动加载、自动加载、手动异步加载和自动异步加载。你可以根据需求选择不同的加载方式,比如做降级或异步操作。 下面是一个使用Caffeine的本地缓存配置类的示例代码: ```java package demo.springboot.config; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.TimeUnit; @Slf4j @Configuration public class CaffeineConfig { @Bean public Cache<String, Object> cache() { final Cache<String, Object> cache = Caffeine.newBuilder() .expireAfterWrite(30, TimeUnit.SECONDS) .initialCapacity(10) .maximumSize(100) .recordStats() .build(); log.info("本地缓存Caffeine初始化完成 ..."); return cache; } } ``` 以上是一个简单的Caffeine缓存工具类的配置,它初始化了一个本地缓存并设置了相关的参数,包括过期时间、初始容量、最大条数等。你可以根据实际需求进行配置和使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [本地缓存天花板-Caffeine](https://blog.csdn.net/weixin_37799575/article/details/128492436)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值