今天對微服務項目中的兩個服務(測試服務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); }