Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get all keys when using POJO as key for Spring Redis cache?

I am using Spring Data Redis to do my caching and I'm caching with the keys as objects, not strings. How do I find all the keys in a cache this way?

When I try to use the StringRedisSerializer() I get a class cast exception saying the object cannot be cast to a string.

When I try the Jackson2JsonRedisSerializer, it throws the exception:

Could not read JSON: Unexpected character ('¬' (code 172)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')

How can I get all the keys?

I'm caching via the @Cacheable annotation.

@EnableCaching
public class RedisCacheConfig
{
    public static final String REDIS_CACHE_MGR = "RedisCacheManager";

    @Value( "${spring.redis.cluster}" )
    private List<String> cluster;

    @Bean
    public JedisConnectionFactory redisConnectionFactory()
    {
        JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(
            new RedisClusterConfiguration( cluster )
        );

        return redisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf)
    {

        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory( cf );
        return redisTemplate;
    }

    @Bean
    public CacheManager redisCacheManager(RedisTemplate redisTemplate) throws EagleCacheException
    {
        RedisCacheManager cacheManager = new RedisCacheManager( redisTemplate );

        cacheManager.setDefaultExpiration( 3600 );

        return cacheManager;
    }
}
like image 890
Don Rhummy Avatar asked Sep 11 '25 19:09

Don Rhummy


1 Answers

Please use

redisTemplate.keys("*")

But before that make sure that your redisTemplate uses correct serializers. In case of string keys:

redisTemplate.setKeySerializer(new StringRedisSerializer())

like image 147
Mike Mike Avatar answered Sep 13 '25 09:09

Mike Mike