Java-ConcurrentHashMap实现缓存、异步

Java-ConcurrentHashMap实现缓存、异步

MyCache.java

package cn.pangpython.test.cache;

/**
 * Created by pangPython on 2017/9/25.
 *
 * 缓存实体类
 */
public class MyCache {
    private String sessionID;//key
    private Object cacheObj;//value
    private long lastAccessTime;//最后访问时间

    public MyCache(String sessionID, Object cacheObj) {
        this.sessionID = sessionID;
        this.cacheObj = cacheObj;
    }

    public MyCache(String sessionID, Object cacheObj, long lastAccessTime) {
        this.sessionID = sessionID;
        this.cacheObj = cacheObj;
        this.lastAccessTime = lastAccessTime;
    }

    public String getSessionID() {
        return sessionID;
    }

    public void setSessionID(String sessionID) {
        this.sessionID = sessionID;
    }

    public Object getCacheObj() {
        return cacheObj;
    }

    public void setCacheObj(Object cacheObj) {
        this.cacheObj = cacheObj;
    }

    public long getLastAccessTime() {
        return lastAccessTime;
    }

    public void setLastAccessTime(long lastAccessTime) {
        this.lastAccessTime = lastAccessTime;
    }
}

CacheManager.java

package cn.pangpython.test.cache;

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

/**
 * Created by pangPython on 2017/9/25.
 */
public class CacheManager {
    private ConcurrentHashMap cacheContainer = null;
    private static volatile CacheManager m_cacheManager = null;
    private long timeout;


    public static CacheManager getInstance() {
        if(m_cacheManager == null){
            synchronized (CacheManager.class){
                if(m_cacheManager == null){
                    m_cacheManager = new CacheManager(1000*60*30);
                }
            }
        }
        return m_cacheManager;
    }

    private CacheManager(long timeout) {
        this.timeout = timeout;
        cacheContainer = new ConcurrentHashMap<>();
        CacheCleaner cacheCleanerThread = new CacheCleaner();
        cacheCleanerThread.start();
    }

    /**
     * 访问缓存
     * 每一次访问把最后访问时间改成当前时间
     *
     * @param key
     * @return
     */
    public MyCache getCache(String key){
        MyCache myCache = cacheContainer.get(key);
        myCache.setLastAccessTime(System.currentTimeMillis());
        cacheContainer.put(key,myCache);
        return myCache;
    }

    /**
     * 添加缓存
     *
     * 默认最后访问时间为当期时间
     * @param key
     * @param value
     */
    public void setCache(String key,MyCache value){
  //      System.out.println("key:"+key);
//        System.out.println("value:"+value);
        MyCache myCache = new MyCache(key,value.getCacheObj());
        myCache.setLastAccessTime(System.currentTimeMillis());
        cacheContainer.put(key,myCache);
    }

    /**
     * 缓存定时清理线程
     *
     */
    class CacheCleaner extends Thread{

        @Override
        public void run() {
            while(true){
                /**
                 * 30分钟执行一次清理
                 *
                 */
                try {
                    Thread.sleep(1000*60*30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                for (Map.Entry entry:cacheContainer.entrySet() ) {
                    String sessionID = entry.getKey();
                    MyCache myCache = entry.getValue();
                    if(System.currentTimeMillis() - myCache.getLastAccessTime() >= timeout){
                        cacheContainer.remove(sessionID);
                    }
                }



            }
        }
    }
}

CacheTest.java

package cn.pangpython.test.cache;

import java.util.Random;

/**
 * Created by pangPython on 2017/9/25.
 */
public class CacheTest {
    public static void main(String[] args){
        /**
         * 比较好的使用场景就是:网络请求的状态下,请求过来,直接返回,然后开启线程操作,修改结果集,供上层轮询调用,实现异步。
         *
         */
        CacheManager cacheManager = CacheManager.getInstance();
        String sessionID = "test_sessionid";
        Integer random_num = new Random().nextInt();
        System.out.println(random_num);
        MyCache myCache = new MyCache(sessionID,random_num);
        cacheManager.setCache(sessionID,myCache);

        //休眠3秒
        try {
            Thread.sleep(1000*3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(cacheManager.getCache(sessionID).getCacheObj().toString());


    }
}

你可能感兴趣的:(Java)