Spring 地图的 CacheEvict
Spring CacheEvict for Map
我有以下缓存方法
@Override
@Cacheable(value = { "timeCache" })
public Map<String, RechargeMatrix> getValues() {
.....
}
它有 58 个值,并且缓存成功。
现在我想驱逐这个缓存中的一个值。哪个
@Override
@CacheEvict(value = "timeCache", key = "#key")
public void clearCache(String key) {
LOG.debug("Clearing cache");
}
上面的代码没有清除缓存值。我觉得我必须提供输入键值才能驱逐特定值。但是说 clearCache("12345");将不起作用,因为它正在寻找字符串值而不是键值..
但不要在#key 中给出..
有什么线索吗?
thanks in advance
您可以做的是清除并立即重新缓存您的 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. This example is based on Memcached Spring Boot library。
更新:
如果您需要 key 参数,如 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 应该具有相同的键值。
我有以下缓存方法
@Override
@Cacheable(value = { "timeCache" })
public Map<String, RechargeMatrix> getValues() {
.....
}
它有 58 个值,并且缓存成功。 现在我想驱逐这个缓存中的一个值。哪个
@Override
@CacheEvict(value = "timeCache", key = "#key")
public void clearCache(String key) {
LOG.debug("Clearing cache");
}
上面的代码没有清除缓存值。我觉得我必须提供输入键值才能驱逐特定值。但是说 clearCache("12345");将不起作用,因为它正在寻找字符串值而不是键值..
但不要在#key 中给出..
有什么线索吗?
thanks in advance
您可以做的是清除并立即重新缓存您的 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. This example is based on Memcached Spring Boot library。
更新:
如果您需要 key 参数,如 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 应该具有相同的键值。