Redis在使用Spring Boot时将对象设置为空json“ {}”

时间:2019-04-05 13:47:58

标签: spring-boot redis spring-data-redis

我正在尝试在Redis上设置对象。 RedisTemplate配置如下所示。

@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
}

这是我的设定行

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

结果是

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

1 个答案:

答案 0 :(得分:1)

如果要存储对象,可以使用哈希

start

RedisTemplate配置

{
  "start": "-P1D",
  "widgets": [
   ...
   ]
}

如果要将其存储为键值对

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());

@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; } 在Redis中的结果 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());