skip to Main Content

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.

2

Answers


  1. 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. This is typically setup in a @Configuration class. Each cache is then just a map of key-value pairs, which is what the application would supply.

    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.

    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.

    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());
        });
      }
    }
    
    Login or Signup to reply.
  2. Quite late for op but in case it helps any visitor. I’d a similar requirement:

    public StringBuffer getAllKeys() {
    
     
       StringBuffer sb = new StringBuffer();
    
       Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());
    
       Iterator<byte[]> it = keys.iterator();
    
       while(it.hasNext()){
    
           byte[] data = (byte[])it.next();
           sb.append(new String(data, 0, data.length));
              }
    
       return sb;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search