记录一次springboot微服务使用Feign远程调用失败

Spring Boot 使用Feign 远程调用失败

1. 源码

最近在学习Spring Boot,在微服务的调用时使用到了 Feign,话不多说直接上代码

@FeignClient(value = FeServiceList.FE_SERVICE_MANAGE_CMS)
public interface CmsPageClient {
    @PostMapping("/cms/page/save")
    CmsPageResult save(@RequestBody CmsPage cmsPage);
}

使用 @FeignClient 注解,配置需要调用的微服务名称,编写接口方法。 项目结构是前后端分离的,统一返回 json。

这是接口返回值对象

@Data
public class CmsPageResult extends ResponseResult {
    CmsPage cmsPage;
    public CmsPageResult(ResultCode resultCode, CmsPage cmsPage) {
        super(resultCode);
        this.cmsPage = cmsPage;
    }
}

2. 遇到的问题

org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: Cannot construct instance of `com.fe.manage_course.client.CmsPageResult`, 
problem: `java.lang.NullPointerException`; nested exception is com.fasterxml.jackson.databind.exc.ValueInstantiationException: 
Cannot construct instance of `com.fe.manage_course.client.CmsPageResult`

大概意思Json解析出错,不能为CmsPageResult构造一个实例。

3. 解决方法

因为CmsPageResult没有显示的空参构造,只有有参构造,所以spring不会提供默认的空参构造。

项目中使用的Lombok,所以只需要在类上添加 @NoArgsConstructor

@Data
@NoArgsConstructor
public class CmsPageResult extends ResponseResult {
    CmsPage cmsPage;
    public CmsPageResult(ResultCode resultCode, CmsPage cmsPage) {
        super(resultCode);
        this.cmsPage = cmsPage;
    }
}

没有使用Lombok,手动加上空参构造即可。

也算是小小的 Feign坑 吧!!!
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐