1. feign自定義Configuration和root 容器有效隔離。
- 用@Configuration注解
- 不能在主@ComponentScan (or @SpringBootApplication)范圍內,從其包名上分離
- 注意避免包掃描重疊,最好的方法是明確的指定包名
2. Spring Cloud Netflix 提供了默認的Bean類型:
- Decoder feignDecoder: ResponseEntityDecoder (which wraps a SpringDecoder)
- Encoder feignEncoder: SpringEncoder
- Logger feignLogger: Slf4jLogger
- Contract feignContract: SpringMvcContract
- Feign.Builder feignBuilder: HystrixFeign.Builder
3. Spring Cloud Netflix沒有提供默認值,但仍然可以在feign上下文配置中創建:
- Logger.Level
- Retryer
- ErrorDecoder
- Request.Options
- Collection
4. 自定義feign的消息編碼解碼器:
不要在如下代碼中getObject方法內new 對象,外部會頻繁調用getObject方法。
1 |
ObjectFactory<HttpMessageConverters> messageConvertersObjectFactory = new ObjectFactory<HttpMessageConverters>() { |
5. 注意測試環境和生產環境,注意正確使用feign日志級別。
6. apacheHttpclient或者其他client的正確配置:
- apacheHttpclient自定義配置放在spring root context,不要在FeignContext,否則不會起作用。
- apacheHttpclient 連接池配置合理地連接和其他參數
7. Feign配置
1 |
#Hystrix支持,如果為true,hystrix庫必須在classpath中 # 日志支持 |
8. Logger.Level支持
必須為每一個Feign Client配置來告訴Feign如何輸出日志,可選:
- NONE, No logging (DEFAULT).
- BASIC, Log only the request method and URL and the response status code and execution time.
- HEADERS, Log the basic information along with request and response headers.
- FULL, Log the headers, body, and metadata for both requests and responses.
9. FeignClient.fallback 正確的使用方法
配置的fallback class也必須在FeignClient Configuration中實例化,否則會報java.lang.IllegalStateException: No fallback instance of type class
異常。
例子:
1 |
public class HystrixClientFallback implements HystrixClient {
|
10. 使用Feign Client 和@RequestMapping時,注意事項
當前工程中有和Feign Client中一樣的Endpoint時,Feign Client的類上不能用@RequestMapping注解否則,當前工程該endpoint http請求且使用accpet時會報404.
下面的例子:
有一個 Controller
1 |
|
有一個Feign Client
1 |
} |
if @RequestMapping is used on class, when invoke http /v1/card/balance, like this :
如果 @RequestMapping注解被用在FeignClient類上,當像如下代碼請求/v1/card/balance時,注意有Accept header:
1 |
Content-Type: application/json POST http://localhost:7913/v1/card/balance |
那么會返回 404。
如果不包含Accept header時請求,則是OK:
1 |
Content-Type:application/json |
或者像下面不在Feign Client上使用@RequestMapping注解,請求也是ok,無論是否包含Accept:
1 |
public interface CardFeignClient {
} |