如果将@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) {
//....
}
}
答案 0 :(得分:1)
缓存对象应为Serializable
,但ResponseEntity
不是Serializable
。
您可以在不同级别添加缓存,因此可以使返回类型可序列化或添加一些能够保存ResponseEntity
的客户序列化器/反序列化器
答案 1 :(得分:-1)
您需要像这样序列化您的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);