从飞书SDK中发现一个小巧优雅的缓存代码(mini版缓存)

188 阅读1分钟

缓存接口

public interface ICache {

    /**
     * 获取缓存值
     *
     * @param key 缓存key
     * @return
     */
    String get(String key);

    /**
     * 获取缓存值,并从缓存中删除该缓存
     *
     * @param key 缓存key
     * @return
     */
    String getRemove(String key);

    /**
     * 设置缓存值
     *
     * @param key      缓存key
     * @param value    缓存值
     * @param expire   超时时间
     * @param timeUnit 时间单位
     */
    void set(String key, String value, int expire, TimeUnit timeUnit);
}

缓存实现

public class LocalCache implements ICache {

    private static final ConcurrentMap<String, Value> CACHE = new ConcurrentHashMap<>(64);
    private LocalCache() {}

    public static LocalCache getInstance() {
        return Inner.LOCAL_CACHE;
    }

    @Override
    public String get(String key) {
        Value v = CACHE.get(key);
        if (v == null || new Date().after(v.end)) {
            CACHE.remove(key);
            return "";
        }
        return v.value;
    }

    @Override
    public String getRemove(String key) {
        String v = get(key);
        if (!"".equals(v)) {
            CACHE.remove(key);
        }
        return v;
    }

    @Override
    public void set(String key, String value, int expire, TimeUnit timeUnit) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, (int) timeUnit.toSeconds(expire));
        Value v = new Value(value, calendar.getTime());
        CACHE.put(key, v);
    }

    /**
     * 内部储存单元
     */
    private static class Value {

        String value;
        Date end;

        public Value(String value, Date time) {
            this.value = value;
            this.end = time;
        }
    }

    /**
     * 静态内部类做单例模式
     */
    private static class Inner {
        private static final LocalCache LOCAL_CACHE = new LocalCache();
    }

HowToUse

public class HowToUseCache {
    public static void main(String[] args) {
        Optional.ofNullable(LocalCache.getInstance())
            .ifPresent(cache -> {
                cache.set("hello", "cache", 10, TimeUnit.SECONDS);
                try {
                    Thread.sleep(9000);
                    // 输出 cache
                    System.out.println(cache.get("hello"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
    }
}