【问题标题】:spring web ResponseEntity can't serializationspring web ResponseEntity不能序列化
【发布时间】:2016-01-25 03:50:24
【问题描述】:

如果使用@Cacheable 返回值'ResponseEntity',我得到序列化错误。

Caused by: 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 payload but received an object of type [org.springframework.http.ResponseEntity]

演示:

@Controller
@CacheConfig(cacheNames = "logs")
public class LogController {
  @Cacheable(key = "#id")
  @RequestMapping(value = LogConstants.LOGS_ID_PATH, method = RequestMethod.GET)
  public ResponseEntity<Log> findById(@PathVariable Long id) {
   //....
  }
}

【问题讨论】:

    标签: spring spring-mvc spring-data spring-data-redis


    【解决方案1】:

    缓存对象应该是Serializable,但ResponseEntity不是Serializable

    您可以在不同级别添加缓存,因此可以使返回类型可序列化或添加一些能够保存ResponseEntity的客户序列化器/反序列化器

    【讨论】:

    • 对我没有用。我的解决方案是创建一个组件作为中间人。
    • 这是不正确的 - 问题不在于 key 不可序列化,而是方法返回类型不可序列化。
    • @Madbreaks 确实是一个错误的答案,谢谢指出
    【解决方案2】:

    您需要像这样序列化您的 ResponseEntity:

    public CustomeResponseEntity extends ResponseEntity implements Serializable {
    
        private static final long serialVersionUID = 7156526077883281625L;
    
        public CustomResponseEntity(HttpStatus status) {
            super(status);
        }
    
        public CustomResponseEntity(Object body, HttpStatus status) {
            super(body, status);
        }
    
        public CustomResponseEntity(MultiValueMap headers, HttpStatus status) {
            super(headers, status);
        }
    
        public CustomResponseEntity(Object body, MultiValueMap headers, HttpStatus status) {
            super(body, headers, status);
        }
    }
    

    然后就可以了。

    return new CustomResponseEntity(resultDTO, HttpStatus.OK);
    

    【讨论】:

    • 你的答案是错误的。是的,ResponseEntity 是可序列化的,但它不是可反序列化的。原因是 ResponseEntity 没有无参数构造函数。但是对于反序列化,应该有一个有效的无参数构造函数。
    猜你喜欢
    • 2020-07-26
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2018-02-07
    • 2016-05-01
    • 2017-04-15
    • 2020-11-21
    相关资源
    最近更新 更多