緩存工具

package com.**.**.service.cache.memory;

import java.util.concurrent.ExecutionException;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.http.client.utils.CloneUtils;
import org.springframework.beans.factory.InitializingBean;

/**
* Copyright © 2007-2016 
* @description gava內存緩存基類
*/

public abstract class AbstractMemoryCache<PK, T> implements InitializingBean {

    private LoadingCache<PK, T> cache;

    protected abstract CacheBuilder<Object, Object> getCacheBuilder(CacheBuilder<Object, Object> cacheBuilder);

    protected abstract CacheLoader<PK, T> getCacheLoader();

    protected LoadingCache<PK, T> getCache() {
        return cache;
    }

    public T getValue(PK pk) throws ExecutionException, CloneNotSupportedException {
        return CloneUtils.cloneObject(this.cache.get(pk));
    }

    public void setValue(PK pk, T t) {
        this.cache.put(pk, t);
    }

    public void invalidKey(PK pk) {
        this.cache.invalidate(pk);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        CacheLoader cacheLoader = this.getCacheLoader();
        CacheBuilder cacheBuilder = this.getCacheBuilder(CacheBuilder.newBuilder());
        this.cache = cacheBuilder.build(cacheLoader);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章