解決SpringCloud Feign傳對象參數調用失敗的問題

SpringCloud Feign傳對象參數調用失敗

  • 不支持GET請求方式
  • 使用Apache HttpClient替換Feign原生httpclient
  • @RequestBody接收json參數

bootstrap-local.yml

feign:
  httpclient:
    enabled: true

pom.xml

<!-- 使用Apache HttpClient替換Feign原生httpclient -->
<dependency>
    <groupId>com.netflix.feign</groupId>
    <artifactId>feign-httpclient</artifactId>
    <version>8.18.0</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

feignClient:

@FeignClient(name = "hd-ucenter-server", fallback = SysTestServerFallbackImpl.class)
public interface SysTestServer { 
    @RequestMapping(value = "/test/test", method = RequestMethod.POST, consumes = "application/json")
    Object test(CurrentUser currentUser);
}

RestController:

@RestController
@PostMapping("/test")
public class TestController {
 
    @RequestMapping(value = "/test")
    public Object test(@RequestBody CurrentUser currentUser) {
        System.out.printf("調用test\n");
       return currentUser;
    }
}

SpringCloud中Feign異常無法傳遞的問題

因為 cloud內部拋出異常不進行處理,Feign獲取spring默認包裝異常結果如下:

{
“timestamp”: “2017-12-27 15:01:53”,
“status”: 500,
“error”: “Internal Server Error”,
“exception”: “com.keruyun.loyalty.commons.master.exception.BusinessException”,
“message”: “Request processing failed; nested exception is {\”code\”:1000, \”message\”:\”test Exception\”}”,
“path”: “/coupon/cloud/commercial/8469”
}

自定義的異常處理下返回狀態

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandlerResolver {
 
    //內部服務異常處理
    @ExceptionHandler(InternalApiException.class)
    public ResultResp<?> handleGlobalException(HttpServletResponse response, InternalApiException internalApiException) {
        ResultResp<?> resultResp = internalApiException.getResultResp();
        log.error(internalApiException.getMessage(), internalApiException);
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());//返回500異常
        response.setContentType(MediaType.APPLICATION_JSON_UTF8.toString());
        return resultResp;
    }
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: