基于 ConcurrentHashMap 的本地缓存工具类

Don’t say much, just go to the code.

package org.bood.common.utils;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 基于 ConcurrentHashMap 的本地缓存工具类
 * 使用 Timer 实现缓存过期功能
 *
 * @author bood
 * @since 2024/01/04
 */
public class CacheUtils {

    /**
     * 默认大小
     */
    private static final int DEFAULT_CAPACITY = 1024;
    /**
     * 最大缓存大小
     */
    private static final int MAX_CAPACITY = 10000;
    /**
     * 1000毫秒
     */
    private static final long SECOND_TIME = 1000;
    /**
     * 默认缓存过期时间
     */
    private static final long DEFAULT_TIMEOUT = 3600 * SECOND_TIME;
    /**
     * 存储缓存的Map
     */
    private static final ConcurrentHashMap<String, Object> map;
    private static final Timer timer;

    static {
        map = new ConcurrentHashMap<>(DEFAULT_CAPACITY);
        timer = new Timer();
    }

    // 防止实例化
    private CacheUtil() {
    }

    static class ClearTask extends TimerTask {
        private final String key;

        public ClearTask(String key) {
            this.key = key;
        }

        @Override
        public void run() {
            // 移除过期的缓存项
            CacheUtil.remove(key);
        }
    }

    public static boolean put(String key, Object object) {
        // 添加缓存项,并设置默认过期时间
        return put(key, object, DEFAULT_TIMEOUT);
    }

    public static boolean put(String key, Object object, long timeout) {
        if (map.size() >= MAX_CAPACITY) {
            return false;
        }
        map.put(key, object);
        // 缓存项到期后自动删除
        timer.schedule(new ClearTask(key), timeout);
        return true;
    }

    public static boolean putAll(Map<String, Object> m, long timeout) {
        if (map.size() + m.size() > MAX_CAPACITY) {
            return false;
        }
        for (Map.Entry<String, Object> entry : m.entrySet()) {
            put(entry.getKey(), entry.getValue(), timeout);
        }
        return true;
    }

    public synchronized static void remove(String key) {
        map.remove(key);
    }

    public static synchronized void clearAll() {
        if (map.size() > 0) {
            map.clear();
        }
        timer.cancel();
    }

    public static Object get(String key) {
        return map.get(key);
    }

    public static boolean contains(String key) {
        return map.containsKey(key);
    }

}

你可能感兴趣的:(瑞士军刀,java,缓存)