redis操作数据时没有序列化:
错误代码:
User user = new User("张三",11);
redisTemplate.opsForValue().set("user",user);
System.out.println(redisTemplate.opsForValue().get("user"));
报错:
org.springframework.data.redis.serializer.SerializationException:
Cannot serialize; nested exception is
org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is
java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable
修改后代码:
//在企业中,我们所有的pojo都会序列化
public class User implements Serializable {
private String name;
private int age;
}
User user = new User("张三",11);
//真实开发一般都是用json来传递对象
String jsonUser = new ObjectMapper().writeValueAsString(user);
redisTemplate.opsForValue().set("user",user);
System.out.println(redisTemplate.opsForValue().get("user"));
完成!!