Java Spring@cacheexecute使用通配符

Java Spring@cacheexecute使用通配符,java,spring,caching,Java,Spring,Caching,有没有办法在@cacheexecute中使用通配符 我有一个具有多租户的应用程序,它有时需要从租户(但不是系统中所有租户)的缓存中逐出所有数据 考虑以下方法: @Cacheable(value="users", key="T(Security).getTenant() + #user.key") public List<User> getUsers(User user) { ... } 还有其他办法吗?答案是:没有 要实现你想要的,这不是一个简单的方法 Spring缓存注释

有没有办法在@cacheexecute中使用通配符

我有一个具有多租户的应用程序,它有时需要从租户(但不是系统中所有租户)的缓存中逐出所有数据

考虑以下方法:

@Cacheable(value="users", key="T(Security).getTenant() + #user.key")
public List<User> getUsers(User user) {
    ...
}
还有其他办法吗?

答案是:没有

要实现你想要的,这不是一个简单的方法

  • Spring缓存注释必须简单,以便于缓存提供程序实现
  • 高效缓存必须简单。有一个键和值。如果在缓存中找到键,则使用该值,否则计算该值并放入缓存。有效密钥必须具有快速且诚实的equals()hashcode()。假设您缓存了来自一个租户的多个对(键、值)。为了提高效率,不同的键应该具有不同的hashcode()。你决定驱逐整个房客。在缓存中查找租户元素并不容易。您必须迭代所有缓存对并丢弃属于租户的对。这是没有效率的。它不是原子的,所以它很复杂,需要一些同步。同步效率不高
  • 因此没有


    但是,如果你找到了一个解决方案,告诉我,因为你想要的功能真的很有用。

    就像宇宙中99%的问题一样,答案是:这取决于你。如果您的缓存管理器实现了一些处理这些问题的功能,那就太好了。但事实似乎并非如此

    如果您使用的是Spring提供的基本内存缓存管理器
    SimpleCacheManager
    ,那么您可能正在使用Spring附带的
    ConcurrentMapCache
    。虽然无法扩展
    ConcurrentMapCache
    来处理密钥中的通配符(因为缓存存储是私有的,您无法访问它),但您可以将其作为自己实现的灵感

    下面是一个可能的实现(我没有真正测试它,只是检查它是否工作)。这是
    ConcurrentMapCache
    的纯拷贝,修改了
    execit()
    方法。不同之处在于,此版本的
    execit()
    处理该键以查看它是否是正则表达式。在这种情况下,它遍历存储中的所有键,并逐出与正则表达式匹配的键

    package com.sigraweb.cache;
    
    import java.io.Serializable;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.ConcurrentMap;
    
    import org.springframework.cache.Cache;
    import org.springframework.cache.support.SimpleValueWrapper;
    import org.springframework.util.Assert;
    
    public class RegexKeyCache implements Cache {
        private static final Object NULL_HOLDER = new NullHolder();
    
        private final String name;
    
        private final ConcurrentMap<Object, Object> store;
    
        private final boolean allowNullValues;
    
        public RegexKeyCache(String name) {
            this(name, new ConcurrentHashMap<Object, Object>(256), true);
        }
    
        public RegexKeyCache(String name, boolean allowNullValues) {
            this(name, new ConcurrentHashMap<Object, Object>(256), allowNullValues);
        }
    
        public RegexKeyCache(String name, ConcurrentMap<Object, Object> store, boolean allowNullValues) {
            Assert.notNull(name, "Name must not be null");
            Assert.notNull(store, "Store must not be null");
            this.name = name;
            this.store = store;
            this.allowNullValues = allowNullValues;
        }
    
        @Override
        public final String getName() {
            return this.name;
        }
    
        @Override
        public final ConcurrentMap<Object, Object> getNativeCache() {
            return this.store;
        }
    
        public final boolean isAllowNullValues() {
            return this.allowNullValues;
        }
    
        @Override
        public ValueWrapper get(Object key) {
            Object value = this.store.get(key);
            return toWrapper(value);
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public <T> T get(Object key, Class<T> type) {
            Object value = fromStoreValue(this.store.get(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.store.put(key, toStoreValue(value));
        }
    
        @Override
        public ValueWrapper putIfAbsent(Object key, Object value) {
            Object existing = this.store.putIfAbsent(key, value);
            return toWrapper(existing);
        }
    
        @Override
        public void evict(Object key) {
            this.store.remove(key);
            if (key.toString().startsWith("regex:")) {
                String r = key.toString().replace("regex:", "");
                for (Object k : this.store.keySet()) {
                    if (k.toString().matches(r)) {
                        this.store.remove(k);
                    }
                }
            }
        }
    
        @Override
        public void clear() {
            this.store.clear();
        }
    
        protected Object fromStoreValue(Object storeValue) {
            if (this.allowNullValues && storeValue == NULL_HOLDER) {
                return null;
            }
            return storeValue;
        }
    
        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 {
        }
    }
    

    同样,这远没有得到正确的测试,但它给了你一种方法去做你想做的事情。如果您使用的是另一个缓存管理器,则可以类似地扩展其缓存实现。

    下面的内容为我在Redis缓存上工作。 假设您要删除所有键前缀为“缓存名称:对象名称:parentKey”的缓存项。使用键值调用方法
    缓存名称:对象名称:parentKey*

    import org.springframework.data.redis.core.RedisOperations;    
    ...
    private final RedisOperations<Object, Object> redisTemplate;
    ...    
    public void evict(Object key)
    {
        redisTemplate.delete(redisTemplate.keys(key));
    }
    
    导入org.springframework.data.redis.core.RedisOperations;
    ...
    私有最终再贴现模板;
    ...    
    公共无效收回(对象键)
    {
    redisTemplate.delete(redisTemplate.keys(key));
    }
    
    从RedisOperations.java

    /**
     * Delete given {@code keys}.
     *
     * @param keys must not be {@literal null}.
     * @return The number of keys that were removed.
     * @see <a href="http://redis.io/commands/del">Redis Documentation: DEL</a>
     */
    void delete(Collection<K> keys);
    
    /**
     * Find all keys matching the given {@code pattern}.
     *
     * @param pattern must not be {@literal null}.
     * @return
     * @see <a href="http://redis.io/commands/keys">Redis Documentation: KEYS</a>
     */
    Set<K> keys(K pattern);
    
    /**
    *删除给定的{@code key}。
    *
    *@param键不能为{@literal null}。
    *@返回已删除的密钥数。
    *@见
    */
    作废删除(收集密钥);
    /**
    *查找与给定{@code pattern}匹配的所有键。
    *
    *@param模式不能为{@literal null}。
    *@返回
    *@见
    */
    设置关键点(K模式);
    
    通过实现自定义缓存解析程序,将租户作为缓存名称的一部分;扩展和实现
    SimpleCacheSolver.getCacheName

    然后逐出所有的钥匙

    @cacheexecute(value={CacheName.CACHE1,CacheName.CACHE2},allEntries=true)


    但请注意,如果您使用redis作为后备缓存,那么引擎盖下的spring将使用KEYS命令,因此解决方案不会扩展。一旦您在redis中获得几个100K密钥,密钥将需要150ms,redis服务器将在CPU上出现瓶颈。顽皮的春天。

    请注意,不建议在生产中使用keys命令。此命令用于调试和特殊操作,如更改键空间布局。不要在常规应用程序代码中使用键
    import org.springframework.data.redis.core.RedisOperations;    
    ...
    private final RedisOperations<Object, Object> redisTemplate;
    ...    
    public void evict(Object key)
    {
        redisTemplate.delete(redisTemplate.keys(key));
    }
    
    /**
     * Delete given {@code keys}.
     *
     * @param keys must not be {@literal null}.
     * @return The number of keys that were removed.
     * @see <a href="http://redis.io/commands/del">Redis Documentation: DEL</a>
     */
    void delete(Collection<K> keys);
    
    /**
     * Find all keys matching the given {@code pattern}.
     *
     * @param pattern must not be {@literal null}.
     * @return
     * @see <a href="http://redis.io/commands/keys">Redis Documentation: KEYS</a>
     */
    Set<K> keys(K pattern);