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> 
Mustafa Güven
  • 15,526
  • 11
  • 63
  • 83

1 Answers1

2

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}

madcolonel10
  • 735
  • 2
  • 9
  • 22
  • 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? – Mustafa Güven Apr 11 '19 at 06:27
  • 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 – madcolonel10 Apr 11 '19 at 12:14