Feign使用和項目集成以及性能優化和使用常見問題


本文內容主要來自

http://www.itmuch.com/spring-cloud-sum/feign-problems/

1、什么是Feign

聲明式http客戶端

2、如何使用

加依賴

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

加注解

@EnableFeignClients

加配置

無寫代碼

package com.fj.xiaofeiyang.pay.api.feignclient;

import com.fj.xiaofeiyang.pay.api.domain.entity.pay.MallPay;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
* @author: yangchun
* @description:
* @date: Created in 2020-02-19 19:17
*/
@FeignClient(name = "pay")
public interface PayFeignClient {
@GetMapping("/mallpay/{id}")
MallPay findById(@PathVariable("id") Integer id);
}
feign的組成
接口             作用           默認值          
Feign.Builder Feign的入口 Feign.Builder
Client Feign底層用什么去發起請求 和Ribbon配合時:LoadBalancerFeignClient,不和Ribbon配合時feign.Client.Defualt
Contract 鍥約支持 Feign不支持springMVC注解,SpringMvcContract
Encoder 編碼器,用於將對象轉換成http消息體 SpringEncoder
Decoder 解碼器,將響應消息體轉換成對象 ResponseEntityDecoder

Logger

日志管理器 Slf4jLogger

RequestInterceptor

用於為每個請求添加通用邏輯










Feign日志
級別           打印內容        
NONE默認值 不記錄日志
BASIC   僅記錄請求方法、URL、響應狀態代碼以及執行時間
HEADERS 記錄BASIC級別的基礎上,記錄請求和響應的header
FULL 記錄請求和響應的header、body和元數據






自定義日志級別
package com.fj.xiaofeiyang.pay.api.feignclient;

import com.fj.xiaofeiyang.pay.api.configuration.PayFeignClientConfiguration;
import com.fj.xiaofeiyang.pay.api.domain.entity.pay.MallPay;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
* @author: yangchun
* @description:
* @date: Created in 2020-02-19 19:17
*/
@FeignClient(name = "pay",configuration = PayFeignClientConfiguration.class)
public interface PayFeignClient {
@GetMapping("/mallpay/{id}")
MallPay findById(@PathVariable("id") Integer id);
}

package com.fj.xiaofeiyang.pay.api.configuration;

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* @author: yangchun
* @description:
* @date: Created in 2020-02-19 20:42
*/
@Configuration
public class PayFeignClientConfiguration {
@Bean
public Logger.Level logLevel(){
return Logger.Level.BASIC;
}
}
 
         
         
        
logging:
level:
com.fj.xiaofeiyang.pay.api.feignclient.PayFeignClient: debug
feign日志時建立再包必須輸出日志上的,所以必須有debug
屬性配置如下
feign:
client:
config:
pay:
loggerLevel: full
以上都是細粒度配置
全局配置兩種方式
java代碼方式
第一種添加Configuration,父子上下文重疊
第二種
@EnableFeignClients(defaultConfiguration = PayFeignClientConfiguration.class)

配置屬性全局配置
feign:
client:
config:
#全局配置
default:
loggerLevel: full
支持的配置項
java代碼方式
配置項           作用          

Logger.level

指定日志級別

Retryer

指定重試策略

ErrorDecodre

指定錯誤解碼器

Request.options

超時

Collection<RequestInterceptor>

攔截器

SelectFactory

用於設置Hystrix配置屬性,Feign整合Hystrix才會使用












屬性配置方式支持的配置項
feign:
client:
config:
#全局配置
default:
loggerLevel: full
connectionTimeout: 5000
readTimeout: 5000
errerDecoder: com.demo.decoder
retryer: com.demo.retryer
requestInterceptors:
- com.demo.FooRequestInterceptor
decode404: false
encoder: com.demo.encoder
decoder: com.demo.decoder
contract: com.demo.Contract
Feign多參數請求
1、GET
@GetMapping("/q")
List<MallPay> query(@SpringQueryMap MallPay mallPay);

第一種不支持繼承


@GetMapping("/q")
List<MallPay> query1(@RequestParam("id") Integer id);


@GetMapping("/q")
List<MallPay> query2(@RequestParam Map<String,Object> mallPay);

@GetMapping("/q")
public List<MallPay> query(MallPay mallPay){
return mallPayMapper.select(mallPay);
}
@GetMapping("/q")
public List<MallPay> query1(MallPay mallPay){
return mallPayMapper.select(mallPay);
}
@GetMapping("/q")
public List<MallPay> query2(MallPay mallPay){
return mallPayMapper.select(mallPay);
}
2、POST
@RequestMapping(value="/q3",method = RequestMethod.POST)
List<MallPay> query3(@RequestBody MallPay mallPay);
 Feign 脫離Ribbon使用如下
@FeignClient(name = "baidu",url = "http://www.baidu.com")
public interface BaiduFeignClient {
@GetMapping
public String index();
}
Feign和RestTemplate對比

角度           RestTemplate              Feign             
可讀性、可維護性   一般 極好
開發體驗 欠佳 極佳
性能 很好 中等RestTemplate50%
靈活性 極佳 中等內置功能可滿足絕大多數需求







Feign的性能優化

1、配置連接池,性能提升15%
2、apache http client 或者okhttp client,下面兩個依賴二選一

<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>10.7.4</version>
</dependency>
配置也是二選一
feign:
client:
config:
#全局配置
default:
loggerLevel: full
httpclient:
enable: true
#最大連接數
max-connection: 200
#單個路徑最大連接數
max-connection-per-route: 50
okhttp:
enable: true
max-connection: 200
#單個路徑最大連接數
max-connection-per-route: 50
3、日志級別最好設置成basic

Feign的常見問題
1、使用案例
使用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>
寫FeignClient
@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();
}
}
}
注意點
@RequestMapping(value = "/upload", method = RequestMethod.POST,
produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  • 中的produeces 、consumes 不能少;

  • 接口定義中的注解@RequestPart(value = "file") 不能寫成@RequestParam(value = "file" 。

  • 最好將Hystrix的超時時間設長一點,例如5秒,否則可能文件還沒上傳完,Hystrix就超時了,從而導致客戶端側的報錯。


使用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>

編寫FeignClient
@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();
}
2、FeignClient接口使用@PathVariable,必須指定value屬性
 
        
@FeignClient("microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET) public User findById(@PathVariable("id") Long id); ... }
3、Java自定義配置類要防止父子上下文重疊
4、Feign注解屬性
@FeignClient(name = "microservice-provider-user") 

在早期的Spring Cloud版本中,無需提供name屬性,從Brixton版開始,@FeignClient必須提供name屬性,否則應用將無法正常啟動!

另外,name、url等屬性支持占位符。例如:

@FeignClient(name = "${feign.name}", url = "${feign.url}")

5、類級別的RequestMapping會被SpringMVC加載
@RequestMapping("/users") @FeignClient(name = "microservice-user") public class TestFeignClient { // ... } 

類上的@RequestMapping 注解也會被Spring MVC加載。該問題現已經被解決,早期的版本有兩種解決方案:

方案1:不在類上加@RequestMapping 注解;

方案2:添加如下代碼:

@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(); } } }
6、首次請求失敗
一、將Hiystrix超時時間設置長
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
二、禁止使用Hystrix超時
hystrix.command.default.execution.timeout.enabled: false
三、feign全局禁止使用Hystrix
feign.hystrix.enabled: false
局部禁止使用Hystrix
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
@GetMapping("/users/{id}")
User findById(@PathVariable("id") Long id);
}
class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder(){
return Feign.builder();
}
}

四、為ribbon配置飢餓加載
ribbon:
eager-load:
enabled: true
clients: client1, client2, client3



7、產生Hystrix監控信息

Feign本身已經整合了Hystrix,可直接使用@FeignClient(value = "microservice-provider-user", fallback = XXX.class) 來指定fallback類,fallback類繼承@FeignClient所標注的接口即可。

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

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

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

第二步:在啟動類上添加@EnableCircuitBreaker 注解,示例:

@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監控數據了。

 
          
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM