[英]How do I get all the keys from a redis cache via Spring Boot with Spring Data Redis 2.x?
I am trying to get the entries in a Spring Boot Cache backed by Redis How do I get all the keys from a redis cache via Spring Boot? I am trying to get the entries in a Spring Boot Cache backed by Redis How do I get all the keys from a redis cache via Spring Boot? uses 1.x of Spring-Data-Redis and the current version uses
DefaultRedisCacheWriter
for the native cache.使用 1.x 的 Spring-Data-Redis 并且当前版本使用
DefaultRedisCacheWriter
作为本机缓存。
I did this several years ago with spring boot 2 (so not sure if this'll work for you with v1), but what I remember is that the Redis cache is actually built upon a number of caches, each having a name.几年前我用 spring boot 2 做到了这一点(所以不确定这是否适用于 v1),但我记得 Redis 缓存实际上是建立在多个缓存之上的,每个缓存都有一个名称。 This is typically setup in a
@Configuration
class.这通常在
@Configuration
class 中设置。 Each cache is then just a map of key-value pairs, which is what the application would supply.然后,每个缓存只是键值对的 map,这是应用程序将提供的。
This is just an example for this use-case (where the developer fully controls the caching), as I wasn't really interested in the Spring-annotated methods for caching method responses.这只是这个用例的一个示例(开发人员完全控制缓存),因为我对用于缓存方法响应的 Spring 注释方法并不真正感兴趣。
In my configuration class, I create a CacheManager
object which is configured with the various caches I intend to use within my application, and those would include the names and their TTL values supplied in a hashmap.在我的配置 class 中,我创建了一个
CacheManager
object,它配置了我打算在我的应用程序中使用的各种缓存,这些缓存将包括 ZDDA7806A4847EC61B5940C2623A5AABD 中提供的名称及其 TTL 值。
Here's some code (untested, so you may need to tweak it):这是一些代码(未经测试,因此您可能需要对其进行调整):
@Autowired
private CacheManager cacheManager;
@Autowired
private RedisTemplate redisTemplate;
public String getValue(String cacheName, String key) {
cacheManager.getCache(cacheName).get(key);
}
public Map<String, String> getCache(String cacheName) {
return redisTemplate
.keys(cacheName+"*")
.parallelStream()
.map(key -> {
Map<String, String> cacheEntries = new HashMap<>();
cacheEntries.put(key, getValue(cacheName, key));
return cacheEntries;
}
)
.collect(Collectors.toList());
}
public void getAllCaches() {
cacheManager.getCacheNames().forEach(cacheName -> {
Map<String, String> cacheObject = getCache(cacheName);
cacheObject.entrySet().stream().peek(entry -> {
System.out.println(entry.getKey() + " = " + entry.getValue());
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.