package com.yiidata.intergration.web.modules.sys.cache;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import java.util.concurrent.Callable;
/**
*
* Icache 缓存的代理,用于支持 Spring CacheManager, @Cacheable
*
*
*
* User: zhenqin
* Date: 15/3/9
* Time: 09:59
*
*
*
* @author zhenqin
*/
public class ProxyCache implements Cache {
/**
* cache 名称
*/
private final String name;
/**
* 实际缓存系统
*/
private final ICache cache;
public ProxyCache(String name, ICache cache) {
this.name = name;
this.cache = cache;
}
public ProxyCache(ICache cache) {
this(cache.getClass().getSimpleName(), cache);
}
@Override
public final String getName() {
return name;
}
@Override
public final Object getNativeCache() {
return cache;
}
@Override
public ValueWrapper get(Object key) {
Object value = this.cache.get(key instanceof String ? (String)key : String.valueOf(key));
return toWrapper(value);
}
public T get(Object key, Class type) {
Object value = this.cache.get(key instanceof String ? (String)key : String.valueOf(key));
if (value != null && type != null && !type.isInstance(value)) {
throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value);
}
return (T) value;
}
@Override
public T get(Object keyO, Callable valueLoader) {
String key = keyO instanceof String ? (String)keyO : String.valueOf(keyO);
return (T)this.cache.get(key);
}
@Override
public void put(Object key, Object value) {
this.cache.add(key instanceof String ? (String)key : String.valueOf(key), value);
}
public ValueWrapper putIfAbsent(Object keyO, final Object value) {
String key = keyO instanceof String ? (String)keyO : String.valueOf(keyO);
Object v = cache.get(key);
if(v == null) {
this.cache.add(key, value);
return toWrapper(value);
}
return null;
}
@Override
public void evict(Object key) {
this.cache.remove(key instanceof String ? (String)key : String.valueOf(key));
}
@Override
public void clear() {
this.cache.clear();
}
private ValueWrapper toWrapper(Object value) {
return (value != null ? new SimpleValueWrapper(value) : null);
}
}