RedisTemplate.opsForValue().set redis赋值实体对象时出现异常。

2023-12-22 12:05:45

异常信息:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is 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.io.NotSerializableException: com.example.sringredis.Models.Book] with root cause

异常代码:controller类

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @GetMapping("/test1")
    public void test1(){
        ValueOperations<String,String> ops1=stringRedisTemplate.opsForValue();
        ops1.set("name","三国演戏");
        String name=ops1.get("name");
        System.out.println(name);
        ValueOperations ops2=redisTemplate.opsForValue();
        Book bk1=new Book();
        bk1.setId(1);
        bk1.setName("红楼梦");
        bk1.setPrice(12.3f);
        bk1.setAuthor("曹雪芹");
        ops2.set("bk1",bk1);
        Book bk2=(Book) ops2.get("bk1");
        System.out.println(bk2);
    }

Book实体类:

public class Book  {
    private Integer id;
    private String name;
    private String author;
    private Float price;
}

解决方案:book实体类,继承?Serializable

修改后的book实体类:

public class Book implements Serializable {
    private Integer id;
    private String name;
    private String author;
    private Float price;
}

运行成功

参考网址:org.springframework.data.redis.serializer.SerializationException: Cannot serialize(解决redis存入对象序列化)_at org.springframework.data.redis.serializer.strin-CSDN博客

文章来源:https://blog.csdn.net/DearXia/article/details/135147143
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。