【缓存】本地缓存三种简单实现方式

本地缓存

1、工具类实现本地缓存

import lombok.Getter;
import lombok.Setter;

/**
 * 本地缓存类
 */
@Getter
@Setter
public class LocalCache implements Comparable<LocalCache> {

    /**
     * 缓存键
     */
    private Object key;

    /**
     * 缓存值
     */
    private Object value;

    /**
     * 最后一次访问时间
     */
    private long lastAccessTime;

    /**
     * 创建时间
     */
    private long createTime;

    /**
     * 过期时间
     */
    private long expireTime;

    /**
     * 缓存命中次数
     */
    private Integer hitCount;

    @Override
    public int compareTo(LocalCache o) {
        return hitCount.compareTo(o.hitCount);
    }
}
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.hihonor.truss.core.core.log.TrussLoggerFactory;

/**
 * 本地缓存工具类
 */
public class LocalCacheUtil<K, V> {
    public static Logger LOGGER = TrussLoggerFactory.getLogger(LocalCacheUtil.class);

    private ConcurrentHashMap<Object, LocalCache> concurrentHashMap;

    final int size;

    public LocalCacheUtil(int capacity) {
        this.size = capacity;
        this.concurrentHashMap = new ConcurrentHashMap<>(capacity);

        // 开启一个线程清理本地过期缓存
        new Thread(new TimeoutTimerThread()).start();
    }

    /**
     * 获取缓存
     *
     * @param key key
     * @return Object
     */
    public Object get(K key) {
        if (concurrentHashMap.isEmpty()) {
            return null;
        }
        if (!concurrentHashMap.containsKey(key)) {
            return null;
        }
        LocalCache cache = concurrentHashMap.get(key);
        if (cache == null) {
            return null;
        }
        cache.setHitCount(cache.getHitCount() + 1);
        cache.setLastAccessTime(System.currentTimeMillis());
        return cache.getValue();
    }

    /**
     * 添加缓存
     *
     * @param key   key
     * @param value value
     */
    public void put(K key, V value, long expire) {
        // The cache is updated when it exists
        if (concurrentHashMap.containsKey(key)) {
            LocalCache cache = concurrentHashMap.get(key);
            cache.setHitCount(cache.getHitCount() + 1);
            cache.setCreateTime(System.currentTimeMillis());
            cache.setLastAccessTime(System.currentTimeMillis());
            cache.setExpireTime(expire * 1000 * 1000 * 1000);
            cache.setValue(value);
            return;
        }

        // The maximum cache has been reached
        if (isFull()) {
            Object kickedKey = getKickedKey();
            if (kickedKey != null) {
                // Remove the least used cache
                concurrentHashMap.remove(kickedKey);
            } else {
                return;
            }
        }
        LocalCache cache = new LocalCache();
        cache.setKey(key);
        cache.setValue(value);
        cache.setCreateTime(System.currentTimeMillis());
        cache.setLastAccessTime(System.currentTimeMillis());
        cache.setHitCount(1);
        cache.setExpireTime(expire * 1000 * 1000 * 1000);
        concurrentHashMap.put(key, cache);
    }

    /**
     * 查询所有缓存
     */
    public void queryCache() {
        if (concurrentHashMap.isEmpty()) {
            LOGGER.info("Cache is empty");
            return;
        }
        Iterator<Map.Entry<Object, LocalCache>> entries = concurrentHashMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Object, LocalCache> entry = entries.next();
            LocalCache value = entry.getValue();
            String localCacheJson = JSONObject.toJSONString(value);
            System.out.println("Key = " + entry.getKey() + ", Value = " + localCacheJson + "\n");
        }
    }


    /**
     * 判断是否达到最大缓存
     *
     * @return boolean
     */
    private boolean isFull() {
        return concurrentHashMap.size() == size;
    }

    /**
     * 获取最少使用的缓存
     *
     * @return Object
     */
    private Object getKickedKey() {
        LocalCache min = Collections.min(concurrentHashMap.values());
        return min.getKey();
    }

    /**
     * 处理过期缓存
     */
    class TimeoutTimerThread implements Runnable {
        public void run() {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(60);

                    // clear expired cache
                    expireCache();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 创建多久后,缓存失效
         *
         * @throws Exception Exception
         */
        private void expireCache() throws Exception {
            LOGGER.info("Check whether the cache is out of date");
            for (Object key : concurrentHashMap.keySet()) {
                LocalCache cache = concurrentHashMap.get(key);
                long timoutTime = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - cache.getCreateTime());
                if (cache.getExpireTime() > timoutTime) {
                    continue;
                }
                LOGGER.info("Clear expired cache key:{}", key);

                // clear expired cache
                concurrentHashMap.remove(key);
            }
        }
    }
}

2、实现简单的Map缓存

/**
 * 本地缓存
 */
private static final ConcurrentHashMap<String, LocalCache> localCache = new ConcurrentHashMap<>(100);

/**
 * 添加缓存
 *
 * @param key key
 * @param value credentials
 * @param expire expire
 */
public void createOrUpdateLocalCache(String key, Credentials value, long expire) {
    // The cache is updated when it exists
    if (localCache.containsKey(key)) {
        LocalCache cache = localCache.get(key);
        cache.setHitCount(cache.getHitCount() + 1);
        cache.setCreateTime(System.currentTimeMillis());
        cache.setLastAccessTime(System.currentTimeMillis());
        cache.setExpireTime(expire * 1000 * 1000 * 1000);
        cache.setValue(value);

        return;
    }

    // The cache is created when it not exists
    LocalCache cache = new LocalCache();
    cache.setKey(key);
    cache.setValue(value);
    cache.setCreateTime(System.currentTimeMillis());
    cache.setLastAccessTime(System.currentTimeMillis());
    cache.setHitCount(1);
    cache.setExpireTime(expire * 1000 * 1000 * 1000);
    localCache.put(key, cache);
}

/**
 * 获取缓存
 *
 * @param key key
 * @return Object
 */
public Object getLocalCache(String key) {
    LocalCache cache = localCache.get(key);
    cache.setHitCount(cache.getHitCount() + 1);
    cache.setLastAccessTime(System.currentTimeMillis());

    return cache.getValue();
}

/**
 * 查询所有缓存
 */
public void queryCache() {
    if (localCache.isEmpty()) {
        LOGGER.info("Cache is empty");
        return;
    }
    for (Map.Entry<String, LocalCache> entry : localCache.entrySet()) {
        LocalCache value = entry.getValue();
        String localCacheJson = JSONObject.toJSONString(value);
        System.out.println("Key = " + entry.getKey() + ", Value = " + localCacheJson + "\n");
    }
}

3、极其简单本地缓存

/**
 * 本地缓存
 */
private static final ConcurrentHashMap<String, Credentials> credentialsLocalCache = new ConcurrentHashMap<>(16);

Credentials alternateCredential = credentialsLocalCache.get(key);

credentialsLocalCache.put(key, alternateCredentials);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值