javaredisjedis

How to read data from Redis cache and query it in Java?


I am new to redis cache i am using core or plain java not spring boot to interact with redis cache. I am able to connect to redis cache using the jedis client but not getting how to retrieve the data using combination of two keys i found a way in spring boot like below but i am unable to find the same in plain java please point me some source where i am unable to find any instructions in redis documentation also around this

@Cacheable(value = "items", key = "#id")
public Item getItem(Integer id) {
    Item item = itemRepository.findById(id).orElseThrow(RuntimeException::new);
    logger.info("Loading data from DB {}", item);
    return item;
}

Solution

  • On plain java, create a RedisTemplate object and then, use it to query your information.

    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);
        config.setUsername(username);
        config.setPassword(password);
        config.setDatabase(db);
        return new JedisConnectionFactory(config);
    }
    
    
    public RedisTemplate<?, ?> redisTemplate() {
        RedisTemplate<?, ?> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(new GenericToStringSerializer<String>(String.class));
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
    

    For example

    redisTemplate.opsForValue().add("key", "value")