Java自定义缓存器

public class CacheManager {
    private static Map<String, CacheData> cache = new ConcurrentHashMap();

    public CacheManager() {
    }

    public static <T> void set(String key, T t) {
        cache.put(key, new CacheManager.CacheData(t, 0L));
    }

    public static <T> void set(String key, T t, long expire) {
        cache.put(key, new CacheManager.CacheData(t, expire));
    }

    public static <T> T get(String key) {
        CacheManager.CacheData<T> data = (CacheManager.CacheData)cache.get(key);
        if (null == data) {
            return null;
        } else if (data.isExpire()) {
            remove(key);
            return null;
        } else {
            return data.getData();
        }
    }

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

    public static void removeAll() {
        cache.clear();
    }

    static {
        Timer t = new Timer();
        t.schedule(new CacheManager.ClearTimerTask(cache), 0L, 60000L);
    }

    private static class ClearTimerTask extends TimerTask {
        Map<String, CacheManager.CacheData> cache;

        public ClearTimerTask(Map<String, CacheManager.CacheData> cache) {
            this.cache = cache;
        }

        public void run() {
            Set<String> keys = this.cache.keySet();
            Iterator var2 = keys.iterator();

            while(var2.hasNext()) {
                String key = (String)var2.next();
                CacheManager.CacheData<?> data = (CacheManager.CacheData)this.cache.get(key);
                if (data.expireTime > 0L && data.expireTime <= Calendar.getInstance().getTimeInMillis()) {
                    this.cache.remove(key);
                }
            }

        }
    }

    private static class CacheData<T> {
        private T data;
        private long expireTime;

        public CacheData(T t, long expire) {
            this.data = t;
            if (expire <= 0L) {
                this.expireTime = 0L;
            } else {
                this.expireTime = Calendar.getInstance().getTimeInMillis() + expire;
            }

        }

        public boolean isExpire() {
            if (this.expireTime <= 0L) {
                return false;
            } else {
                return this.expireTime <= Calendar.getInstance().getTimeInMillis();
            }
        }

        public T getData() {
            return this.data;
        }
    }
}

提供了基本的缓存增删、过期等方法,使用于单机情况,测试使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值