I am using SpringBoot with Redis And want to serial object UserDO into Json, store it in Redis, and get the json data, reverse it into UserDO Object.This is UserDO
public class UserDO {String name;int age;String password;// Getters and Setters are not here
}This is how I set the Serializer:
@Configuration
public class RedisTemplateConfiguration {
@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 使用Jackson2JsonRedisSerialize 替换默认序列化 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); // 设置key和value的序列化规则 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // 设置hashKey和hashValue的序列化规则 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // 设置支持事物 //redisTemplate.setEnableTransactionSupport(true); redisTemplate.afterPropertiesSet(); return redisTemplate;}
}
It works when I use redisTemplate.opsForValue().set("user-service:user:2",userDO);
But when I Run uo = (UserDO)redisTemplate.opsForValue().get("user-service:user:2")
I got a LinkedHashMap
@Testvoid testSeriable(){ User user = new User(); user.setAge(18); user.setName("William"); user.setPwd("testpwd"); redisTemplate.opsForValue().set("user:2", user); System.out.println(redisTemplate.opsForValue().get("user:2").getClass()); Map<String, String> res = ((LinkedHashMap<String, String>)redisTemplate.opsForValue().get("user:2")); System.out.println(res); /* class java.util.LinkedHashMap {name=William, age=18, pwd=testpwd} */ redisTemplate.opsForList().leftPushAll("testkey", user, user, user); List<User> list = redisTemplate.opsForList().range("testkey", 0, -1); System.out.println(list); /* This works fine! [{name=William, age=18, pwd=testpwd}, {name=William, age=18, pwd=testpwd}, {name=William, age=18, pwd=testpwd}] */}
So How can I get User directly from redisTemplate.opsForList().get() ?