JAVA 简单缓存实现-nacos

4 篇文章 1 订阅
1 篇文章 0 订阅

定义缓存接口:

public interface Cache<K, V> {

    /**
     * Cache a pair of key value. If the key value already exists, the value will be overwritten.
     * @param key cache key
     * @param val cache value
     */
    void put(K key, V val);
    
    /**
     * Take the corresponding value from the cache according to the cache key.
     * @param key cache key
     * @return cache value
     */
    V get(K key);
    
    /**
     * Get the value in the cache according to the primary key, and put it into the cache after processing by the function.
     * @param key cache key
     * @param call a function, the return value of the function will be updated to the cache
     * @return cache value
     * @throws Exception callable function interface throw exception
     */
    V get(K key, Callable<? extends V> call) throws Exception;
    
    /**
     * Take the corresponding value from the cache according to the cache key, and remove this record from the cache.
     * @param key cache key
     * @return cache value
     */
    V remove(K key);
    
    /**
     * Clear the entire cache.
     */
    void clear();
    
    /**
     * Returns the number of key-value pairs in the cache.
     * @return  number of key-value pairs
     */
    int getSize();
}

基于Java-Map的本地缓存实现:

public class SimpleCache<K, V> implements Cache<K, V> {
    
    private Map<K, V> cache;
    
    public SimpleCache(int size) {
        cache = new HashMap<>(size);
    }
    
    @Override
    public void put(K key, V val) {
        cache.put(key, val);
    }
    
    @Override
    public V get(K key) {
        return cache.get(key);
    }
    
    @Override
    public V get(K key, Callable<? extends V> call) throws Exception {
        if (cache.containsKey(key)) {
            return cache.get(key);
        } else {
            V v2 = call.call();
            cache.put(key, v2);
            return v2;
        }
    }
    
    @Override
    public V remove(K key) {
        return cache.remove(key);
    }
    
    @Override
    public void clear() {
        cache.clear();
    }
    
    @Override
    public int getSize() {
        return cache.size();
    }
}

基于LinkedHashMap的LruCache实现:

public class LruCache<K, V> implements Cache<K, V> {
    
    private final Cache<K, V> delegate;
    
    private Map<K, V> keyMap;
    
    private K eldestKey;
    
    public LruCache(Cache<K, V> delegate, int size) {
        this.delegate = delegate;
        setSize(size);
    }
    
    @Override
    public int getSize() {
        return delegate.getSize();
    }
    
    public void setSize(final int size) {
        keyMap = new LinkedHashMap<K, V>(size, .75F, true) {
            private static final long serialVersionUID = 4267176411845948333L;
            
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                boolean tooBig = size() > size;
                if (tooBig) {
                    eldestKey = eldest.getKey();
                }
                return tooBig;
            }
          
        };
    }
    
    @Override
    public void put(K key, V val) {
        delegate.put(key, val);
        cycleKeyList(key);
    }
    
    @Override
    public V get(K key) {
        keyMap.get(key);
        return delegate.get(key);
    }
    
    @Override
    public V get(K key, Callable<? extends V> call) throws Exception {
        return this.delegate.get(key, call);
    }
    
    @Override
    public V remove(K key) {
        return delegate.remove(key);
    }
    
    @Override
    public void clear() {
        delegate.clear();
        keyMap.clear();
    }
    
    private void cycleKeyList(K key) {
        keyMap.put(key, null);
        if (eldestKey != null) {
            delegate.remove(eldestKey);
            eldestKey = null;
        }
    }
    
}

自动过期缓存实现:

public class AutoExpireCache<K, V> implements Cache<K, V> {
    
    private long expireNanos;
    
    private Cache<K, V> delegate;
    
    private HashMap<K, CacheItemProperties> keyProp = new HashMap<>();
    
    public AutoExpireCache(Cache<K, V> delegate, long expireNanos) {
        this.expireNanos = expireNanos;
        this.delegate = delegate;
    }
    
    @Override
    public void put(K key, V val) {
        keyProp.put(key, cacheItemProperties());
        this.delegate.put(key, val);
    }
    
    @Override
    public V get(K key) {
        if (keyProp.get(key) != null && isExpire(keyProp.get(key))) {
            this.keyProp.remove(key);
            this.delegate.remove(key);
            return null;
        }
        return this.delegate.get(key);
    }

    @Override
    public V get(K key, Callable<? extends V> call) throws Exception {
        V cachedValue = this.get(key);
        if (null == cachedValue) {
            V v2 = call.call();
            this.put(key, v2);
            return v2;

        }
        return cachedValue;

    }
    
    @Override
    public V remove(K key) {
        keyProp.remove(key);
        return this.delegate.remove(key);
    }
    
    @Override
    public void clear() {
        keyProp.clear();
        this.delegate.clear();
    }
    
    @Override
    public int getSize() {
        return this.delegate.getSize();
    }
    
    private boolean isExpire(CacheItemProperties itemProperties) {
        if (itemProperties == null) {
            return true;
        }
        return expireNanos != -1 && (System.nanoTime() - itemProperties.getExpireNanos() > expireNanos);
    }
    
    private CacheItemProperties cacheItemProperties() {
        CacheItemProperties cacheItemProperties = new CacheItemProperties();
        cacheItemProperties.setExpireNanos(System.nanoTime());
        return cacheItemProperties;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java缓存实现demo完整实例,很不错的资源,欢迎大家来下载学习。/** * 此函数接受一个对象列表,数目不定,opration:表是触发的事件 * eg:change;fnClear:表示初始化下拉框。var_args表示多个下拉框... */ function bindSelects(operation, initSelectObj, loadShow, var_args){ //每个argument对象都有一个 change事件 //change事件会触发:此argument之后的对象清空,紧跟此对象的后一对象发送ajax请求 var elementList = []; for (var i = 3; arguments[i]; i++) { elementList[i-3] = arguments[i]; } for (var i = 0; elementList[i]; i++) { (function(k) { elementList[k].bind(operation, function(){ selectType = elementList[k].attr("name"); //其后的对象进行某个操作 for (var j = k+1; elementList[j]; j++) { if (initSelectObj && initSelectObj.constructor===Function) { if(elementList[k].val() == "") { initSelectObj(elementList[j],elementList[j].data(SELECT_KEY)); LOAD_KEYS[j].hide(); } else{ initSelectObj(elementList[j],elementList[j].data(SELECT_KEY)); } } } //紧跟对象发送ajax if (elementList[k+1]) { if(elementList[k].val() != "") { //从页面缓存中取出 if(elementList[k+1].data(elementList[k].val())) { var data = elementList[k+1].data(elementList[k].val()); var key=LIST_KEYS[k]; var jsonKey = [key]; addContentToSelect(data,jsonKey,elementList[k+1]); } else { //从缓存中取出数据 if (fnAjax && fnAjax.constructor===Function) { loadShow(LOAD_KEYS[k+1]); fnAjax(elementList[k+1].data(SELECT_KEY),LIST_KEYS[k],LOAD_KEYS[k+1],elementList[k],selectType); } } } } }); })(i); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值