今天对微服务项目中的两个服务(测试服务demo、分类服务Category)进行服务的发现。由Category服务访问Demo服务的getById接口,在服务发现的过程中
发生了报错:
There was an unexpected error (type=Internal Server Error, status=500). Error while extracting response for type [com.kerry.common.consts.ServerResponse<com.kerry.demo.pojo.Demo>] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.kerry.common.consts.ServerResponse` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.kerry.common.consts.ServerResponse` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (PushbackInputStream); line: 1, column: 2] 翻译如下
起初犯得小问题以为是服务发现没有找到对应的服务进行远程调用,于是查看了Eureka注册中心是否注册上了服务,经过检查发现两个服务都是正常的注册上了注册中心
随后查看Category服务上的DemoClient上的服务发现Name是否传递正确,查看后发现也没问题
由此得来在服务发现上是没有问题的,此时回去再观察报错的问题,通过翻译后观察报错可以发现我们的错误是500.
也就是我们是服务器内部出现了错误,然后可以看到问题出在了JSON解析上,我项目的统一返回实例ServerResponse
无法进行JSON的解析
既然找到了问题,接下来就是百度查看问题的解决方式:
解决问题链接:https://www.cnblogs.com/fengli9998/p/7590864.html
百度后得知,由于我们的返回实例提供的都是带参的实例,类中没有无参构造,导致Feign获取到数据后无法进行JSON的解析。
解决:
在ServerResponse实例类上添加上Lombok的@NoArgsConstructor注解(添加上无参构造函数)
代码如下:
DemoController
public class DemoController { @GetMapping("/{id}") public ServerResponse<Demo> getById(@PathVariable Integer id){ return ServerResponse.createBySuccess(demoService.getById(id)); } }
CategoryManagerController
@RestController @RequestMapping("/admin/category") public class CategoryManagerController { @Autowired private DemoFeignClient demoFeignClient; //Feign服务发现测试接口 @RequestMapping(value = "demo.do",method = RequestMethod.GET) public ServerResponse<Demo> feignDemo() { ServerResponse<Demo> resp = demoFeignClient.getById(1); //ServerResponse<Demo> resp = ServerResponse.createBySuccess(new Demo()); return resp; } }
DemoFeignClient
@FeignClient(value= "service-demo") public interface DemoFeignClient { //调用的请求路径 @RequestMapping(value = "/demo/{id}",method = RequestMethod.GET) public ServerResponse<Demo> getById(@PathVariable Integer id); }