123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- 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
- *
- * <pre>
- *
- * User: zhenqin
- * Date: 15/3/9
- * Time: 09:59
- *
- * </pre>
- *
- * @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> T get(Object key, Class<T> 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> T get(Object keyO, Callable<T> 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);
- }
- }
|