0

I'm trying to set an object on redis. RedisTemplate configuration is shown below.

@Bean
fun redisTemplate(): RedisTemplate<String, Any> {
    val redisTemplate = RedisTemplate<String, Any>()
    redisTemplate.connectionFactory = jedisConnectionFactory()
    redisTemplate.defaultSerializer = GenericJackson2JsonRedisSerializer()
    redisTemplate.keySerializer = StringRedisSerializer()
    redisTemplate.hashKeySerializer = GenericJackson2JsonRedisSerializer()
    redisTemplate.valueSerializer = GenericJackson2JsonRedisSerializer()

    redisTemplate.afterPropertiesSet()
    return redisTemplate
}

here is my setting line

redisUtil.redisTemplate().opsForValue().set("CATEGORIES", tree)

and the result is

127.0.0.1:6379> keys *
1) "CATEGORIES"
127.0.0.1:6379> GET CATEGORIES
"{}"
127.0.0.1:6379> 

1 Answer 1

2
+50

If you want to store an object you can use hash

Pet pet = new Pet();
pet.setHeight(10);
pet.setName("tommy");

ObjectMapper oMapper = new ObjectMapper();

template.opsForHash().putAll("pet", oMapper.convertValue(pet, Map.class));

Pet pet1 = oMapper.convertValue(template.opsForHash().entries("pet"), Pet.class);
System.out.println(pet1.getName());
System.out.println(pet1.getHeight());
System.out.println(pet1.getWeight());

RedisTemplate configuration

@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(jedisConnectionFactory());
template.setEnableTransactionSupport(true);
return template;
}

If you want to store it as a key value pair

Pet pet = new Pet();
pet.setHeight(10);
pet.setName("tommy");

template.opsForValue().set("pettest", pet);
Pet pet2 = (Pet) template.opsForValue().get("pettest");
System.out.println("boo boo");
System.out.println(pet2.getName());

result of get pettest in redis {"@class":"com.cisco.rediscluster.Pet","name":"tommy","height":10}

Sign up to request clarification or add additional context in comments.

2 Comments

I can but should I?, I mean isn't there a way to store an object as whole rather than a part of map? If no, why?
the second part of my answer is storing the entire object, you just have to type cast it to the correct class when reading the data, in your case Tree

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.