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);
}
}