org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Cannot construct instance of `com.example.learn_1.entity.LearnUser` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (byte[])"["com.example.learn_1.entity.LearnUser",{"userId":null,"userName":"嗩吶","userAge":988,"remark":null}]"; line: 1, column: 42]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.example.learn_1.entity.LearnUser` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
代碼
RedisConfig
@Bean("userRedistemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
// 將剛才的redis連接工廠設(shè)置到模板類中
template.setConnectionFactory(redisConnectionFactory);
// 設(shè)置key的序列化器
template.setKeySerializer(new StringRedisSerializer());
// 設(shè)置value的序列化器
//使用Jackson 2,將對象序列化為JSON
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//json轉(zhuǎn)對象類减细,不設(shè)置默認(rèn)的會將json轉(zhuǎn)成hashmap
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
return template;
}
entity
@Data
@Builder
@Accessors(chain = true)
public class LearnUser //extends BaseEntity
{
private static final long serialVersionUID = 1L;
@TableId(value = "user_id", type = IdType.AUTO)
private Integer userId;
private String userName;
private Integer userAge;
private String remark;
}
test
@Test
public void testRedisTemplate(){
// 以注解的形式把 bean 注入Spring 并獲取 Spring 的上下文環(huán)境
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);
// 獲取自己配置的 bean 實例
RedisTemplate template = ctx.getBean(RedisTemplate.class);
LearnUser user = LearnUser.builder().userAge(988).userName("嗩吶").build();
template.opsForValue().set("key1", user);
System.out.println(template.opsForValue().get("key1"));
}