spring 3.2 集成Guava Cache遇到的问题

6081745-bd10e7246f9273f3.png
砥砺前行

因为接手的老项目使用的spring3.2版本,guava18。

首先将spring4中的 GuavaCacheManagerGuavaCache 拷贝到项目中。

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheBuilderSpec;
import com.google.common.cache.CacheLoader;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class GuavaCacheManager implements CacheManager {

    private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>(16);

    private boolean dynamic = true;

    private CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();

    private CacheLoader<Object, Object> cacheLoader;

    private boolean allowNullValues = true;


    /**
     * Construct a dynamic GuavaCacheManager,
     * lazily creating cache instances as they are being requested.
     */
    public GuavaCacheManager() {
    }

    /**
     * Construct a static GuavaCacheManager,
     * managing caches for the specified cache names only.
     */
    public GuavaCacheManager(String... cacheNames) {
        setCacheNames(Arrays.asList(cacheNames));
    }


    /**
     * Specify the set of cache names for this CacheManager's 'static' mode.
     * <p>The number of caches and their names will be fixed after a call to this method,
     * with no creation of further cache regions at runtime.
     */
    public void setCacheNames(Collection<String> cacheNames) {
        if (cacheNames != null) {
            for (String name : cacheNames) {
                this.cacheMap.put(name, createGuavaCache(name));
            }
            this.dynamic = false;
        }
    }

    /**
     * Set the Guava CacheBuilder to use for building each individual
     * {@link GuavaCache} instance.
     * @see #createNativeGuavaCache
     * @see CacheBuilder#build()
     */
    public void setCacheBuilder(CacheBuilder<Object, Object> cacheBuilder) {
        Assert.notNull(cacheBuilder, "CacheBuilder must not be null");
        this.cacheBuilder = cacheBuilder;
    }

    /**
     * Set the Guava CacheBuilderSpec to use for building each individual
     * {@link GuavaCache} instance.
     * @see #createNativeGuavaCache
     * @see CacheBuilder#from(CacheBuilderSpec)
     */
    public void setCacheBuilderSpec(CacheBuilderSpec cacheBuilderSpec) {
        this.cacheBuilder = CacheBuilder.from(cacheBuilderSpec);
    }

    /**
     * Set the Guava cache specification String to use for building each
     * individual {@link GuavaCache} instance. The given value needs to
     * comply with Guava's {@link CacheBuilderSpec} (see its javadoc).
     * @see #createNativeGuavaCache
     * @see CacheBuilder#from(String)
     */
    public void setCacheSpecification(String cacheSpecification) {
        this.cacheBuilder = CacheBuilder.from(cacheSpecification);
    }

    /**
     * Set the Guava CacheLoader to use for building each individual
     * {@link GuavaCache} instance, turning it into a LoadingCache.
     * @see #createNativeGuavaCache
     * @see CacheBuilder#build(CacheLoader)
     * @see com.google.common.cache.LoadingCache
     */
    public void setCacheLoader(CacheLoader<Object, Object> cacheLoader) {
        this.cacheLoader = cacheLoader;
    }

    /**
     * Specify whether to accept and convert {@code null} values for all caches
     * in this cache manager.
     * <p>Default is "true", despite Guava itself not supporting {@code null} values.
     * An internal holder object will be used to store user-level {@code null}s.
     */
    public void setAllowNullValues(boolean allowNullValues) {
        this.allowNullValues = allowNullValues;
    }

    /**
     * Return whether this cache manager accepts and converts {@code null} values
     * for all of its caches.
     */
    public boolean isAllowNullValues() {
        return this.allowNullValues;
    }


    @Override
    public Collection<String> getCacheNames() {
        return Collections.unmodifiableSet(this.cacheMap.keySet());
    }

    @Override
    public Cache getCache(String name) {
        Cache cache = this.cacheMap.get(name);
        if (cache == null && this.dynamic) {
            synchronized (this.cacheMap) {
                cache = this.cacheMap.get(name);
                if (cache == null) {
                    cache = createGuavaCache(name);
                    this.cacheMap.put(name, cache);
                }
            }
        }
        return cache;
    }

    /**
     * Create a new GuavaCache instance for the specified cache name.
     * @param name the name of the cache
     * @return the Spring GuavaCache adapter (or a decorator thereof)
     */
    protected Cache createGuavaCache(String name) {
        return new GuavaCache(name, createNativeGuavaCache(name), isAllowNullValues());
    }

    /**
     * Create a native Guava Cache instance for the specified cache name.
     * @param name the name of the cache
     * @return the native Guava Cache instance
     */
    protected com.google.common.cache.Cache<Object, Object> createNativeGuavaCache(String name) {
        if (this.cacheLoader != null) {
            return this.cacheBuilder.build(this.cacheLoader);
        }
        else {
            return this.cacheBuilder.build();
        }
    }

}
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * Spring {@link Cache} adapter implementation on top of a
 * Guava {@link com.google.common.cache.Cache} instance.
 *
 * <p>Requires Google Guava 12.0 or higher.
 *
 * @author Juergen Hoeller
 * @author Stephane Nicoll
 * @since 4.0
 */
public class GuavaCache implements Cache {

    private static final Object NULL_HOLDER = new NullHolder();

    private final String name;

    private final com.google.common.cache.Cache<Object, Object> cache;

    private final boolean allowNullValues;


    /**
     * Create a {@link GuavaCache} instance.
     * @param name the name of the cache
     * @param cache backing Guava Cache instance
     */
    public GuavaCache(String name, com.google.common.cache.Cache<Object, Object> cache) {
        this(name, cache, true);
    }

    /**
     * Create a {@link GuavaCache} instance.
     * @param name the name of the cache
     * @param cache backing Guava Cache instance
     * @param allowNullValues whether to accept and convert null values for this cache
     */
    public GuavaCache(String name, com.google.common.cache.Cache<Object, Object> cache, boolean allowNullValues) {
        Assert.notNull(name, "Name must not be null");
        Assert.notNull(cache, "Cache must not be null");
        this.name = name;
        this.cache = cache;
        this.allowNullValues = allowNullValues;
    }


    @Override
    public final String getName() {
        return this.name;
    }

    @Override
    public final com.google.common.cache.Cache<Object, Object> getNativeCache() {
        return this.cache;
    }

    public final boolean isAllowNullValues() {
        return this.allowNullValues;
    }

    @Override
    public ValueWrapper get(Object key) {
        Object value = this.cache.getIfPresent(key);
        return toWrapper(value);
    }

    @SuppressWarnings("unchecked")
    public <T> T get(Object key, Class<T> type) {
        Object value = fromStoreValue(this.cache.getIfPresent(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 void put(Object key, Object value) {
        this.cache.put(key, toStoreValue(value));
    }

    public ValueWrapper putIfAbsent(Object key, final Object value) {
        try {
            PutIfAbsentCallable callable = new PutIfAbsentCallable(value);
            Object result = this.cache.get(key, callable);
            return (callable.called ? null : toWrapper(result));
        } catch (ExecutionException e) {
            throw new IllegalArgumentException(e);
        }
    }

    @Override
    public void evict(Object key) {
        this.cache.invalidate(key);
    }

    @Override
    public void clear() {
        this.cache.invalidateAll();
    }


    /**
     * Convert the given value from the internal store to a user value
     * returned from the get method (adapting {@code null}).
     * @param storeValue the store value
     * @return the value to return to the user
     */
    protected Object fromStoreValue(Object storeValue) {
        if (this.allowNullValues && storeValue == NULL_HOLDER) {
            return null;
        }
        return storeValue;
    }

    /**
     * Convert the given user value, as passed into the put method,
     * to a value in the internal store (adapting {@code null}).
     * @param userValue the given user value
     * @return the value to store
     */
    protected Object toStoreValue(Object userValue) {
        if (this.allowNullValues && userValue == null) {
            return NULL_HOLDER;
        }
        return userValue;
    }

    private ValueWrapper toWrapper(Object value) {
        return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
    }


    @SuppressWarnings("serial")
    private static class NullHolder implements Serializable {
    }

    private class PutIfAbsentCallable implements Callable<Object> {
        private boolean called;

        private final Object value;

        private PutIfAbsentCallable(Object value) {
            this.value = value;
        }

        @Override
        public Object call() throws Exception {
            called = true;
            return toStoreValue(value);
        }
    }

}

接着在spring中集成guava cache:

@Configuration
@EnableCaching(proxyTargetClass = true)
public class CacheConfig {
    @Value("${cache.guava.priceChange.maxSize}")
    private long priceChangeMaxSize;

    @Value("${cache.guava.priceChange.duration}")
    private long priceChangeDuration;

    @Bean
    public CacheManager cacheManager() {
        GuavaCacheManager cacheManager = new GuavaCacheManager();
        cacheManager.setCacheBuilder(CacheBuilder
                .newBuilder()
                .expireAfterWrite(priceChangeDuration, TimeUnit.HOURS)
                .maximumSize(priceChangeMaxSize));
        return cacheManager;
    }
}

使用cache:

@Cacheable(value = "priceCache", key = "{#requestVo.startDate}-{#requestVo.endDate}-{#requestVo.matchType}")
public Object getObject(xxx requestVo){
    Object result = null;
    ....
    return result;
}

public Object getC(xxx requestVo){
    xxxx;
    getObject(requestVo);
    xxxx;
    return xxx;
}

注意:

如果我们的getObject方法是被同一个类中的另一个方法调用,那么这里的cache将失效,因为getObject必须通过代理对象调用才能起作用。如果需要在getC调用时 使得getObject缓存起作用,需要做如下声明:

<aop:aspectj-autoproxy proxy-target-class="true" expose-proxy="true"/>

expose-proxy 设置为true。

并且在代码中将调用getObject方法做进一步修改:

public Object getC(xxx requestVo){
    xxxx;
    ((CurrentClass)AopContext.currentProxy()).getObject(requestVo);
    xxxx;
    return xxx;
}

这样在getC调用getObject时,缓存也将生效。

转载于:https://www.jianshu.com/p/29a2f8889c3e

猜你喜欢

转载自blog.csdn.net/weixin_33786077/article/details/91281910