Search code examples
javaspringspring-bootcachingspring-data-redis

How do I get all the keys from a redis cache via Spring Boot?


I have a service method that caches with redis cache via Spring Boot (using compile("org.springframework.boot:spring-boot-starter-data-redis:1.5.6.RELEASE")):

@Cacheable( value = "test" )
public CacheTestObject getTestObject(String name)
{
    return new CacheTestObject( name );
}

This works but when i try to get all the keys (and see it there) I get:

//This returns 0 keys
( ( RedisTemplate ) cacheManager.getCache("test").getNativeCache() ).keys( "*" )

But this returns true:

( ( RedisTemplate ) cacheManager.getCache("test").getNativeCache() ).hasKey( "Joe" )

And the following are all:

//TRUE
( ( RedisTemplate ) cacheManager.getCache("test").getNativeCache() ).hasKey( "Joe" )

//TRUE
( ( RedisTemplate ) cacheManager.getCache("test").getNativeCache() ).hasKey( "J*e" )

//FALSE
( ( RedisTemplate ) cacheManager.getCache("test").getNativeCache() ).hasKey( "Jo*" )

//FALSE
( ( RedisTemplate ) cacheManager.getCache("test").getNativeCache() ).hasKey( "*oe" )

//FALSE
( ( RedisTemplate ) cacheManager.getCache("test").getNativeCache() ).hasKey( "*" )

Why is this? Why can't I get all keys with the pattern ""? Or even "J"?

If I do any pattern query where "*" is first or last, it returns no keys.


Solution

  • Make sure that redisTemplate autowired into your cacheManager uses correct serializers. In case of string keys:

    redisTemplate.setKeySerializer(new StringRedisSerializer())