用于Map的Spring CacheEvict

时间:2017-10-31 23:49:32

标签: spring memcached

我有以下缓存方法

function kids(node) {
    return node.items
        ? [{...node, items: []}, _.map(node.items, kids)]
        : {...node, items: null};
}

_.flatMapDeep(data, kids);

它有58个值,并且成功缓存。 现在我想在这个缓存中逐出一个值。这

    @Override
    @Cacheable(value = { "timeCache" })
    public Map<String, RechargeMatrix> getValues() {
         .....
    }

上面的代码没有清除缓存值。我觉得我必须给出用于驱逐特定值的输入键值。但是说clearCache(“12345”);将无法工作,因为它正在寻找字符串值而不是键值。
但是不要如何给#key .. 任何线索?

    @Override
    @CacheEvict(value = "timeCache", key = "#key")
    public void clearCache(String key) {
        LOG.debug("Clearing cache"); 
    }

1 个答案:

答案 0 :(得分:2)

您可以做的是清除并立即重新缓存 timeCache ,例如您的 clearCache 方法应该修改如下:

@CacheEvict(value = "timeCache", allEntries = true, beforeInvocation = true)
@Cacheable("timeCache")
public Map<String, RechargeMatrix> clearAndRecache() {
    // retrieve your timeCache values as in getValues() method
}

您可以在示例项目here中查看此内容。此示例基于Memcached Spring Boot library

<强>更新

如果您需要 clearCache(String key)中的参数来删除数据库中的数据,那么您的代码应如下所示:

@CacheEvict(value = "timeCache", allEntries = true, beforeInvocation = true)
@Cacheable(value = "timeCache", key = "T(org.springframework.cache.interceptor.SimpleKey).EMPTY")
public Map<String, RechargeMatrix> deleteAndRecache(String key) {
    // 1. delete data in DB by key parameter 
    // 2. retrieve your timeCache values as in getValues() method and return it
}

所有这一切的原因是 getValues()方法将使用值为SimpleKey.EMPTY的密钥缓存memcached中的数据。因此,此方法中返回的Map应具有相同的键值。