首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Spring @CacheEvict使用通配符

Spring @CacheEvict使用通配符
EN

Stack Overflow用户
提问于 2013-07-19 22:46:26
回答 6查看 10.7K关注 0票数 16

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

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

考虑以下方法:

代码语言:javascript
复制
@Cacheable(value="users", key="T(Security).getTenant() + #user.key")
public List<User> getUsers(User user) {
    ...
}

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

代码语言:javascript
复制
@CacheEvict(value="users", key="T(Security).getTenant() + *")
public void deleteOrganization(Organization organization) {
    ...
}

有没有办法做到这一点?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2016-11-18 23:29:06

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

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

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

代码语言:javascript
复制
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 {
    }
}

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

代码语言:javascript
复制
@CacheEvict(value = { "cacheName" }, key = "'regex:#tenant'+'.*'")
public myMethod(String tenant){
...
}

同样,这还远远没有经过适当的测试,但它为您提供了一种做您想做的事情的方法。如果您正在使用另一个缓存管理器,则可以以类似的方式扩展其缓存实现。

票数 3
EN

Stack Overflow用户

发布于 2013-11-05 05:09:39

答案是:不。

而且实现你想要的东西也不是一件容易的事情。

  1. Spring Cache注解必须简单,易于通过缓存实现provider.
  2. Efficient缓存必须简单。有一个键和一个值。如果在缓存中找到key,则使用该值,否则计算值并将其放入缓存。Efficient key必须具有快速诚实的equals()hashcode()。假设您缓存了来自一个租户的多个对(键、值)。为了提高效率,不同的键应该有不同的hashcode()。你决定把整个房客赶出去。在缓存中查找租户元素并非易事。您必须迭代所有缓存的对,并丢弃属于租户的对。它的效率不高。它不是原子的,所以它很复杂,需要一些同步。同步效率不高。

因此,不是。

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

票数 6
EN

Stack Overflow用户

发布于 2018-06-25 22:19:30

下面是我在Redis Cache上的工作。假设您想删除所有关键字前缀为' Cache -name:object-name:parentKey‘的cache条目。调用键值为cache-name:object-name:parentKey*的方法。

代码语言:javascript
复制
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

代码语言:javascript
复制
/**
 * 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);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17749049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档