自定义缓存实现

自定义缓存类
可增加是否需要持久化

package *.*.*.*;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;

@Component
public class DocumentCache {

	private static final Logger logger = Logger.getLogger(DocumentCache.class);

	private static DocumentCache instance;

	private static final ConcurrentHashMap<String, Entry> map = new ConcurrentHashMap<String, Entry>();

	private static final long cacheTimeout = 30 * 60 * 1000;

	private static final long timerTimeout = 60 * 1000;

	private static final Timer cleanTimer = new Timer("ATP-DocumentCache-CleanTimer");

	private DocumentCache() {
		cleanTimer.scheduleAtFixedRate(new TimerTask(){
			public void run()
			{
				try {
					removeCash(map);
				} catch (Throwable e) {
					logger.error("ATP-DocumentCache-CleanTimer fail" + e);
				}
			}
		},0,timerTimeout);
	}

	private class Entry {
		long time;
		Object value;

		Entry(Object value){
			this.value = value;
			this.time = System.currentTimeMillis();
		}

		public Object getValue() {
			return value;
		}

		public Long getTime() {
			return time;
		}
	}

	public static DocumentCache getDocumentCacheInstance() {
		if (null == instance) {
			synchronized (DocumentCache.class) {
				if (null == instance)
					instance = new DocumentCache();
			}
		}
		return instance;
	}

	/**
	 * 往缓存中添加一个对象
	 */
	public void put(String k, Object v) {
		this.map.put(k, new Entry(v));
	}

	/**
	 * 从缓存中获取一个对象
	 */
	public Object get(String k) {
		return this.map.get(k).getValue();
	}

	/**
	 * 缓存达到30分钟清除缓存
	 * @param map
	 */
	public void removeCash(ConcurrentHashMap<String, Entry> map){
		long now = System.currentTimeMillis();
		for(String key : map.keySet()){
			Entry entry = map.get(key);
			if(now - entry.time > cacheTimeout){
				map.remove(key);
			}
		}
	}
}

使用redisson实现缓存持久化

package *.*.*.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.redisson.api.*;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Component
public class DocumentCache {

    private static final Logger logger = Logger.getLogger(DocumentCache.class);

    private static DocumentCache instance;

    private static final ConcurrentHashMap<String, Entry> map = new ConcurrentHashMap<String, Entry>();

    private static RMapCache<String, String> redisDocMap = null;

    private static final long cacheTimeout = 30 * 60 * 1000;

    private static final long timerTimeout = 60 * 1000;

    private static final Timer cleanTimer = new Timer("ATP-DocumentCache-CleanTimer");

    // 临时
    private static final String TEMP_DOCUMENT_KEY_NAME = "***";

    @Autowired
    private RedissonClient redissonClient;

    public DocumentCache() {
        cleanTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                try {
                    removeCash(map);
                } catch (Throwable e) {
                    logger.error("ATP-DocumentCache-CleanTimer fail", e);
                }
            }
        }, 0, timerTimeout);
    }

    @PostConstruct
    public void init() {
        instance = this;
        instance.redissonClient = this.redissonClient;
        // 获取缓存Map集合
        redisDocMap = redissonClient.getMapCache(TEMP_DOCUMENT_KEY_NAME, new StringCodec());
    }

    public static DocumentCache getDocumentCacheInstance() {
        if (null == instance) {
            synchronized (DocumentCache.class) {
                if (null == instance)
                    instance = new DocumentCache();
            }
        }
        return instance;
    }

    private class Entry {
        private long time;
        private Object value;

        Entry(Object value) {
            this.value = value;
            this.time = System.currentTimeMillis();
        }
    }

    /**
     * 往缓存中添加一个对象
     */
    public void put(String k, Object v) {
        // 保存缓存
        redisDocMap.put(k, JSON.toJSONString(v), cacheTimeout, TimeUnit.MILLISECONDS);
        // 保存内存
        this.map.put(k, new Entry(v));
    }

    /**
     * 从缓存中获取一个对象
     */
    public Object get(String k) {
        Object o = this.map.get(k);
        // 从缓存中读取
        if (null != o) {
            o = ((Entry) o).value;
        }
        if (null == o) {
            // 从redis中读取
            String documentStr = redisDocMap.get(k);
            if (documentStr.startsWith("[")) {
                o = JSONObject.parseArray(documentStr, ***.class);
            } else {
                o = JSONObject.parseObject(documentStr, ***.class);
            }
        }
        return o;
    }

    /**
     * 清除老化对象
     *
     * @param map
     */
    public void removeCash(ConcurrentHashMap<String, Entry> map) {
        long now = System.currentTimeMillis();
        for (String key : map.keySet()) {
            Entry entry = map.get(key);
            if (now - entry.time >= cacheTimeout) {
                // 清理缓存
                redisDocMap.remove(key);
                // 清除内存数据
                map.remove(key);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值