Spring Cloud Feign 總結問題,注意點,性能調優,切換okhttp3

Feign常見問題總結

FeignClient接口如使用@PathVariable ,必須指定value屬性git

//在一些早期版本中, @PathVariable("id") 中的 "id" ,也就是value屬性,必須指定,不能省略。
@FeignClient("microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
  public User findById(@PathVariable("id") Long id);
  ...
}複製代碼

Java代碼自定義Feign Client的注意點與坑github

@FeignClient(name = "microservice-provider-user", configuration = UserFeignConfig.class)
public interface UserFeignClient {
  @GetMapping("/users/{id}")
  User findById(@PathVariable("id") Long id);
}

/**
 * 該Feign Client的配置類,注意:
 * 1. 該類能夠獨立出去;
 * 2. 該類上也可添加@Configuration聲明是一個配置類;
 * 配置類上也可添加@Configuration註解,聲明這是一個配置類;
 * 但此時千萬別將該放置在主應用程序上下文@ComponentScan所掃描的包中,
 * 不然,該配置將會被全部Feign Client共享,沒法實現細粒度配置!
 * 我的建議:像我同樣,不加@Configuration註解
 *
 * @author zhouli
 */
class UserFeignConfig {
  @Bean
  public Logger.Level logger() {
    return Logger.Level.FULL;
  }
}複製代碼
  • 配置類上也可添加@Configuraiton 註解,聲明這是一個配置類;但此時千萬別將該放置在主應用程序上下文@ComponentScan 所掃描的包中,不然,該配置將會被全部Feign Client共享(至關於變成了通用配置,其實本質仍是Spring父子上下文掃描包重疊致使的問題),沒法實現細粒度配置!
  • 我的建議:像我同樣,不加@Configuration註解,免得進坑。
  • 最佳實踐:儘可能用配置屬性自定義Feign的配置!!!

@FeignClient 註解屬性web

//@FeignClient(name = "microservice-provider-user")
//在早期的Spring Cloud版本中,無需提供name屬性,從Brixton版開始,@FeignClient必須提供name屬性,不然應用將沒法正常啓動!
//另外,name、url等屬性支持佔位符。例如:
@FeignClient(name = "${feign.name}", url = "${feign.url}")複製代碼

類級別的@RequestMapping會被Spring MVC加載spring

@RequestMapping("/users")
@FeignClient(name = "microservice-user")
public class TestFeignClient {
    // ...
}複製代碼

類上的@RequestMapping 註解也會被Spring MVC加載。該問題現已經被解決,早期的版本有兩種解決方案:方案1:不在類上加@RequestMapping 註解;方案2:添加以下代碼:json

@Configuration
@ConditionalOnClass({ Feign.class })
public class FeignMappingDefaultConfiguration {
    @Bean
    public WebMvcRegistrations feignWebRegistrations() {
        return new WebMvcRegistrationsAdapter() {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                return new FeignFilterRequestMappingHandlerMapping();
            }
        };
    }

    private static class FeignFilterRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
        @Override
        protected boolean isHandler(Class<?> beanType) {
            return super.isHandler(beanType) && !beanType.isInterface();
        }
    }
}複製代碼

首次請求失敗Ribbon的飢餓加載(eager-load)模式性能優化

如需產生Hystrix Stream監控信息,須要作一些額外操做Feign自己已經整合了Hystrix,可直接使用@FeignClient(value = "microservice-provider-user", fallback = XXX.class) 來指定fallback類,fallback類繼承@FeignClient所標註的接口便可。app

可是假設如需使用Hystrix Stream進行監控,默認狀況下,訪問http://IP:PORT/actuator/hystrix.stream 是會返回404,這是由於Feign雖然整合了Hystrix,但並無整合Hystrix的監控。如何添加監控支持呢?須要如下幾步:ide

第一步:添加依賴,示例:wordpress

<!-- 整合hystrix,其實feign中自帶了hystrix,引入該依賴主要是爲了使用其中的hystrix-metrics-event-stream,用於dashboard -->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>複製代碼

第二步:在啓動類上添加@EnableCircuitBreaker 註解,示例:post

@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
@EnableCircuitBreaker
public class MovieFeignHystrixApplication {
  public static void main(String[] args) {
    SpringApplication.run(MovieFeignHystrixApplication.class, args);
  }
}複製代碼

第三步:在application.yml中添加以下內容,暴露hystrix.stream端點:

management:
  endpoints:
    web:
      exposure:
        include: 'hystrix.stream'複製代碼

這樣,訪問任意Feign Client接口的API後,再訪問http://IP:PORT/actuator/hystrix.stream ,就會展現一大堆Hystrix監控數據了。

原文連接:http://www.itmuch.com/spring-cloud-sum/feign-problems/

Feign 上傳文件

加依賴

<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>3.0.3</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form-spring</artifactId>
    <version>3.0.3</version>
</dependency>複製代碼

編寫Feign Client

@FeignClient(name = "ms-content-sample", configuration = UploadFeignClient.MultipartSupportConfig.class)
public interface UploadFeignClient {
    @RequestMapping(value = "/upload", method = RequestMethod.POST,
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    String handleFileUpload(@RequestPart(value = "file") MultipartFile file);

    class MultipartSupportConfig {
        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder();
        }
    }
}複製代碼

如代碼所示,在這個Feign Client中,咱們引用了配置類MultipartSupportConfig ,在MultipartSupportConfig 中,咱們實例化了SpringFormEncoder 。這樣這個Feign Client就可以上傳啦。

注意點

//RequestMapping註解中的produeces 、consumes 不能少;
@RequestMapping(value = "/upload", method = RequestMethod.POST,
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)複製代碼
  • 接口定義中的註解@RequestPart(value = "file") 不能寫成@RequestParam(value = "file")
  • 最好將Hystrix的超時時間設長一點,例如5秒,不然可能文件還沒上傳完,Hystrix就超時了,從而致使客戶端側的報錯。

原文連接:http://www.itmuch.com/spring-cloud-sum/spring-cloud-feign-upload/

Feign實現Form表單提交

添加依賴:

<dependency>
  <groupId>io.github.openfeign.form</groupId>
  <artifactId>feign-form</artifactId>
  <version>3.2.2</version>
</dependency>
<dependency>
  <groupId>io.github.openfeign.form</groupId>
  <artifactId>feign-form-spring</artifactId>
  <version>3.2.2</version>
</dependency>複製代碼

Feign Client示例:

@FeignClient(name = "xxx", url = "http://www.itmuch.com/", configuration = TestFeignClient.FormSupportConfig.class)
public interface TestFeignClient {
    @PostMapping(value = "/test",
            consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE},
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
            )
    void post(Map<String, ?> queryParam);

    class FormSupportConfig {
        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;
        // new一個form編碼器,實現支持form表單提交
        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
        // 開啓Feign的日誌
        @Bean
        public Logger.Level logger() {
            return Logger.Level.FULL;
        }
    }
}複製代碼

調用示例:

@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
  HashMap<String, String> param = Maps.newHashMap();
  param.put("username","zhangsan");
  param.put("password","pwd");
  this.testFeignClient.post(param);
  return new User();
}複製代碼

日誌:

...[TestFeignClient#post] ---> POST http://www.baidu.com/test HTTP/1.1
...[TestFeignClient#post] Accept: application/json;charset=UTF-8
...[TestFeignClient#post] Content-Type: application/x-www-form-urlencoded; charset=UTF-8
...[TestFeignClient#post] Content-Length: 30
...[TestFeignClient#post] 
...[TestFeignClient#post] password=pwd&username=zhangsan
...[TestFeignClient#post] ---> END HTTP (30-byte body)複製代碼

由日誌可知,此時Feign已能使用Form表單方式提交數據。

原文連接:http://www.itmuch.com/spring-cloud-sum/feign-form-params/

Feign GET請求如何構造多參數

假設需請求的URL包含多個參數,例如http://microservice-provider-user/get?id=1&username=張三 ,該如何使用Feign構造呢?咱們知道,Spring Cloud爲Feign添加了Spring MVC的註解支持,那麼咱們不妨按照Spring MVC的寫法嘗試一下:

@FeignClient("microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User get0(User user);
}複製代碼

然而,這種寫法並不正確,控制檯會輸出相似以下的異常。

feign.FeignException: status 405 reading UserFeignClient#get0(User); content:
{"timestamp":1482676142940,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/get"}複製代碼

由異常可知,儘管咱們指定了GET方法,Feign依然會使用POST方法發送請求。因而致使了異常。正確寫法以下

方法一[推薦]注意:使用該方法沒法使用Fegin的繼承模式

@FeignClient("microservice-provider-user")
public interface UserFeignClient {
  @GetMapping("/get")
  public User get0(@SpringQueryMap User user);
}複製代碼

方法二[推薦]

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User get1(@RequestParam("id") Long id, @RequestParam("username") String username);
}複製代碼

這是最爲直觀的方式,URL有幾個參數,Feign接口中的方法就有幾個參數。使用@RequestParam註解指定請求的參數是什麼。

方法三[不推薦]多參數的URL也可以使用Map來構建。當目標URL參數很是多的時候,可以使用這種方式簡化Feign接口的編寫。

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User get2(@RequestParam Map<String, Object> map);
}複製代碼

在調用時,可以使用相似如下的代碼。

public User get(String username, String password) {
  HashMap<String, Object> map = Maps.newHashMap();
  map.put("id", "1");
  map.put("username", "張三");
  return this.userFeignClient.get2(map);
}複製代碼

注意:這種方式不建議使用。主要是由於可讀性很差,並且若是參數爲空的時候會有一些問題,例如map.put("username", null); 會致使服務調用方(消費者服務)接收到的username是"" ,而不是null。

原文連接:http://www.itmuch.com/spring-cloud-sum/feign-multiple-params-2/

切換爲 Okhttp3 提高 QPS 性能優化

加依賴引入okhttp3

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-okhttp</artifactId>
    <version>${version}</version>
</dependency>複製代碼

寫配置

feign:
  # feign啓用hystrix,才能熔斷、降級
  # hystrix:
  # enabled: true
  # 啓用 okhttp 關閉默認 httpclient
  httpclient:
    enabled: false #關閉httpclient
    # 配置鏈接池
    max-connections: 200 #feign的最大鏈接數
    max-connections-per-route: 50 #fegin單個路徑的最大鏈接數
  okhttp:
    enabled: true
  # 請求與響應的壓縮以提升通訊效率
  compression:
    request:
      enabled: true
      min-request-size: 2048
      mime-types: text/xml,application/xml,application/json
    response:
      enabled: true複製代碼

參數配置

/**
 * 配置 okhttp 與鏈接池
 * ConnectionPool 默認建立5個線程,保持5分鐘長鏈接
 */
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class) //SpringBoot自動配置
public class OkHttpConfig {

    // 默認老外留給你彩蛋中文亂碼,加上它就 OK
    @Bean
    public Encoder encoder() {
        return new FormEncoder();
    }

    @Bean
    public okhttp3.OkHttpClient okHttpClient() {
        return new okhttp3.OkHttpClient.Builder()
                //設置鏈接超時
                .connectTimeout(10, TimeUnit.SECONDS)
                //設置讀超時
                .readTimeout(10, TimeUnit.SECONDS)
                //設置寫超時
                .writeTimeout(10, TimeUnit.SECONDS)
                //是否自動重連
                .retryOnConnectionFailure(true)
                .connectionPool(new ConnectionPool(10, 5L, TimeUnit.MINUTES))
                .build();
    }
}複製代碼

原文連接:https://mp.weixin.qq.com/s/PAjXS9d6Sxa04pw1Lw2HXQ

趙小胖我的博客

相關文章
相關標籤/搜索