Java自定義LRU緩存實現

KelDandridg 9年前發布 | 1K 次閱讀 Java Freelancer

自定義LRU緩存實現
</div>

 

Cache緩存接口    

public interface Cache {
    /**
     * 緩存ID
     * @return
     */
    String getId(); 
    Object get(String key);
    void put(String key,Object value);
    void clear();
    void remove(String key);
    int size();
}

LRUCacheImpl    

public class LRUCacheImpl implements Cache {
    private long timeout=0; //0代表永不超時
    private Map<Object,CacheEntry> cache=null;
    private String id;
    public LRUCacheImpl(String id,int maxsize,long timeout){
        this.timeout=timeout;
        this.cache=new LRULinkedHashMap(maxsize);
        this.id=id;
    }
    public LRUCacheImpl(int maxsize,long timeout){
        this.timeout=timeout;
        this.cache=new LRULinkedHashMap(maxsize);
        this.id=UUID.randomUUID().toString();
    }

    @Override
    public String getId() {
        // TODO Auto-generated method stub
        return this.id;
    }


    @Override
    public Object get(String key) {
        // TODO Auto-generated method stub
        Object value=null;
        CacheEntry entry;
        synchronized (this) {
            entry=cache.get(key);
        }
        if(entry!=null){
            //如果沒有超時,或者超時設置為0
            if((System.currentTimeMillis()-entry.getTimeCached())<timeout||timeout==0){
                value=entry.getValue();
            }else{
                cache.remove(key);
            }
        }
        return value;
    }


    @Override
    public synchronized void put(String key, Object value) {
        // TODO Auto-generated method stub
        cache.put(key, new DefaultCacheEntry(value, System.currentTimeMillis()));
    }

    @Override
    public synchronized void clear() {
        // TODO Auto-generated method stub
        cache.clear();
    }


    @Override
    public synchronized void remove(String key) {
        // TODO Auto-generated method stub
        cache.remove(key);
    }

    @Override
    public int size() {
        // TODO Auto-generated method stub
        return cache.size();
    }
}

[代碼]LRULinkedHashMap     

public class LRULinkedHashMap extends LinkedHashMap<Object, CacheEntry>{
    private int maxSize;
    public LRULinkedHashMap(int maxsize){
        super(maxsize/2+1,0.75f,true);
        this.maxSize=maxsize;
    }
    /* 
     * 當緩存數超過最大容量時,返回true把最后一個移除。 
     * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry)
     */
    @Override
     protected boolean removeEldestEntry(Map.Entry eldest) {
        return size()>maxSize;
    }
}

[代碼]CacheFactory     

public interface CacheFactory {
    Cache createCache(String id,int maxsize,long timeout);
}

[代碼]LRUCacheFactory     

public class LRUCacheFactory implements CacheFactory{

    @Override
    public Cache createCache(String id, int maxsize, long timeout) {
        // TODO Auto-generated method stub
        return new LRUCacheImpl(id,maxsize,timeout);
    }

}

[代碼]CacheEntry    

public interface CacheEntry {
    /**
     * 加入緩存時的時間
     * @return
     */
    long getTimeCached();
    Object getValue();
}

[代碼]DefaultCacheEntry     

public class DefaultCacheEntry implements CacheEntry{
    private long timecached=-1;
    private Object value;
    public DefaultCacheEntry(Object value,long timecached){
        this.value=value;
        this.timecached=timecached;
    }

    @Override
    public long getTimeCached() {
        // TODO Auto-generated method stub
        return timecached;
    }

    @Override
    public Object getValue() {
        // TODO Auto-generated method stub
        return value;
    }

}

[代碼]CacheManager    

public class CacheManager{
    private static final ConcurrentHashMap<String, Cache> caches=new ConcurrentHashMap<>();
    /**
     * 緩存策略枚舉
     */
    public static enum CacheStrategy{
        LRU
    }

    /**
     * 
     * @param maxsize
     * @param timeout
     * @param strategy 可為null。默認LRU
     * @return
     */
        public static Cache createCache(int maxsize, long timeout,CacheStrategy strategy) {
        if(strategy==null){
            strategy=CacheStrategy.LRU;
        }
        Cache cache=getCacheFactory(strategy).createCache(UUID.randomUUID().toString(),maxsize, timeout);
        caches.putIfAbsent(cache.getId(), cache);
        return cache;
    }
    private static CacheFactory getCacheFactory(CacheStrategy strategy){
        CacheFactory factory=null;
        if("LRU".equals(strategy.name())){
            factory=new LRUCacheFactory();
        }
        return factory;
    }
    public static Cache getCacheById(String cacheId){
        return caches.get(cacheId);
    }
    public static void clear(){
        caches.clear();
    }
    public static void remove(String cacheId){
        caches.remove(cacheId);
    }

}
 本文由用戶 KelDandridg 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!