Feign & Ribbon开发配置

  1. 配置log
    Feign - 图5
  2. 配置log 配置文件
    Feign - 图6

    配置文件配置

    同样也要先配置log打印级别:
    Feign - 图7
    image.png
    全局配置
    image.png

Feign配置

image.png

Feign中的RequestParam,RequestBody,SpringQueryMap

  • @RequestParam:get传参,只能基本类型
  • @SpringQueryMap:get传参,对象类型
  • @RequestBody:post传参

image.png

【Feign优化】Feign默认是URLConnection可替换为HttpClient

URLConnection没有连接池。

  1. 加依赖

image.png

  1. 写配置

image.png
默认的defaultMaxPerRoute=2,maxTotal=20
image.png
【Spring Cloud】详解Feign常用配置 - SegmentFault 思否
Feign的性能优化 - 简书

【Feign优化】Feign压缩

image.png
推荐

Feign整合Hystrix

  1. 配置feign.hystrix.enabled:true
  2. 设置@FeignClient注解的fallback和fallbackFactory

image.png
fallbackFactory优点就是可以获得异常Exception。
image.png

Feign配置HystrixProperty

@HystrixProperty only works with @HystrixCommand, not @RequestMapping and @FeignClient. Generally setting hystrix properties in application.properties works

只能通过配置文件配置Hystrix的断路器。
image.png

Feign整合Sentinel

  1. @FeignClient(name = "user-center",
  2. // fallback = UserCenterFeignClientFallback.class,
  3. fallbackFactory = UserCenterFeignClientFallbackFactory.class
  4. )

fallback不可以接收异常,fallbackFactory可以

【坑】Feign传递token【RequestInterceptor】

  • @RequestHeader
  • RequestInterceptor

image.png

  1. @Slf4j
  2. @Configuration
  3. public class FeignConfig {
  4. /**
  5. * <h2>给 Feign 配置请求拦截器</h2>
  6. * RequestInterceptor 是我们提供给 open-feign 的请求拦截器, 把 Header 信息传递
  7. * */
  8. @Bean
  9. public RequestInterceptor headerInterceptor() {
  10. return template -> {
  11. ServletRequestAttributes attributes =
  12. (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  13. if (null != attributes) {
  14. HttpServletRequest request = attributes.getRequest();
  15. Enumeration<String> headerNames = request.getHeaderNames();
  16. if (null != headerNames) {
  17. while (headerNames.hasMoreElements()) {
  18. String name = headerNames.nextElement();
  19. String values = request.getHeader(name);
  20. // 不能把当前请求的 content-length 传递到下游的服务提供方, 这明显是不对的
  21. // 请求可能一直返回不了, 或者是请求响应数据被截断
  22. if (!name.equalsIgnoreCase("content-length")) {
  23. // 这里的 template 就是 RestTemplate
  24. template.header(name, values);
  25. }
  26. }
  27. }
  28. }
  29. };
  30. }
  31. }

使用 feign 调用服务时,Post 变 Get 请求的解决方案 - 知乎