1. 主要依賴
XXXClient主要依賴的是openfeign:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
2. FeignClient不支持PATCH方法
引入httpclient依賴(注意時適配feign-core版本):
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>10.4.0</version>
</dependency>
3. 關於服務熔斷 hystrix
在微服務調用之間,使用FeignClient如果不使用服務熔斷,只要xxxClient內部除了異常,調用方得到的信息始終是500(拿不到那些業務相關的異常),爲了讓xxxClient內部的異常直接拋到調用方,可以如下配置(就算調用方已經定義全局異常處理也不會捕獲FeignClient的異常),使用方式如下:
// 1. 在定義client時加入fallbackFactory
@FeignClient(value = "test-client", url = "http://localhost:8087/gjw-shop", fallbackFactory = TestFeignErrorFallback.class)
public interface TestClient {
//...各種方法
void fun1();
}
// 2. 定義TestFeignErrorFallback類(建議一個Client定義一個)
@Component
public class FeignErrorFallback implements FallbackFactory<TestClient> {
private static final Logger LOG = LoggerFactory.getLogger(FeignErrorFallback.class);
public static final String DEFAULT_ERR_MSG = "======= error occurred in server =======";
@Override
public TestClient create(Throwable throwable) {
String msg = throwable == null ? DEFAULT_ERR_MSG : throwable.getMessage();
if (!StringUtils.isEmpty(msg)) {
LOG.error(msg);
}
return new TestClient() {
@Override
public void fun1(Long shopComponentId) {
throw new RuntimeException(msg);
}
};
}
}
// 3. 在xxxClient調用方加入服務熔斷配置
# 開啓熔斷
feign.hystrix.enabled = true