16

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

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

考虑以下方法:

@Cacheable(value="users", key="T(Security).getTenant() + #user.key")
public List<User> getUsers(User user) {
    ...
}

所以,我想做类似的事情:

@CacheEvict(value="users", key="T(Security).getTenant() + *")
public void deleteOrganization(Organization organization) {
    ...
}

有什么办法吗?

4

6 回答 6

6

答案是:没有。

实现你想要的并不是一件容易的事。

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

因此没有。

但是,如果您找到解决方案,请告诉我,因为您想要的功能非常有用。

于 2013-11-04T21:09:39.360 回答
3

就像宇宙中 99% 的问题一样,答案是:视情况而定。如果您的缓存管理器实现了一些处理该问题的东西,那就太好了。但情况似乎并非如此。

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

下面有一个可能的实现(除了检查它是否工作之外,我并没有真正测试它)。ConcurrentMapCache这是对方法进行修改的普通副本evict()。不同的是,这个版本的evict()处理关键是看它是否是一个正则表达式。在这种情况下,它会遍历存储中的所有键并逐出与正则表达式匹配的键。

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 {
    }
}

我相信读者知道如何使用自定义缓存实现来初始化缓存管理器。有很多文档可以向您展示如何做到这一点。正确配置项目后,您可以像这样正常使用注解:

@CacheEvict(value = { "cacheName" }, key = "'regex:#tenant'+'.*'")
public myMethod(String tenant){
...
}

同样,这远未得到正确测试,但它为您提供了一种方法来做您想做的事。如果您使用另一个缓存管理器,您可以类似地扩展其缓存实现。

于 2016-11-18T15:29:05.717 回答
2

下面在 Redis Cache 上为我工作。假设您要删除所有带有键前缀的缓存条目:'cache-name:object-name:parentKey'。使用键值调用方法cache-name:object-name:parentKey*

import org.springframework.data.redis.core.RedisOperations;    
...
private final RedisOperations<Object, Object> redisTemplate;
...    
public void evict(Object key)
{
    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);
于 2018-06-25T14:19:30.463 回答
0

我想从缓存中删除所有存储的订单,并以这种方式进行了编译。

@CacheEvict(value = "List<Order>", allEntries = true)

据我了解,这种方式将删除使用此值存储的所有列表。所以你可以创建另一个结构,它也可以是一种解决方案。

于 2022-01-05T16:11:29.813 回答
0

我也有类似的问题。我就是这样解决的。

我的配置类

@Bean
RedisTemplate redisTemplate() {
    RedisTemplate template = new RedisTemplate();
    template.setConnectionFactory(lettuceConnectionFactory());
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new RedisSerializerGzip());
    return template;
}

我的实用类

public class CacheService {

    final RedisTemplate redisTemplate;

    public void evictCachesByPrefix(String prefix) {
        Set<String> keys = redisTemplate.keys(prefix + "*");
        for (String key : keys) {
            redisTemplate.delete(key);
        }
    }
}

警告:将 KEYS 视为仅应极其小心地在生产环境中使用的命令。当它针对大型数据库执行时,它可能会破坏性能。 https://redis.io/commands/keys

于 2021-11-09T14:07:45.183 回答
0

通过实现自定义 CacheResolver 将租户作为缓存名称的一部分;扩展和实施SimpleCacheResolver.getCacheName

然后驱逐所有密钥

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

但请注意,如果您使用 redis 作为后备缓存,那么 spring 在后台使用 KEYS 命令,因此该解决方案将无法扩展。一旦你在 redis 中获得了几个 100K 的密钥,KEYS 将花费 150 毫秒,并且 redis 服务器将在 CPU 上出现瓶颈。顽皮的春天。

于 2020-08-27T00:46:01.130 回答