天天看點

feign簡介與實戰一、JAVA 項目中實作遠端接口調用二、feign簡介三、feign使用四、Spring Cloud Feign的自定義配置及使用

一、JAVA 項目中實作遠端接口調用

1)Httpclient

HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支援 Http 協定的用戶端程式設計工具包,并且它支援 HTTP 協定最新版本和建議。HttpClient 相比傳統 JDK 自帶的 URLConnection,提升了易用性和靈活性,使用戶端發送 HTTP 請求變得容易,提高了開發的效率。

2)Okhttp

一個處理網絡請求的開源項目,是安卓端最火的輕量級架構,由 Square 公司貢獻,用于替代 HttpUrlConnection 和 Apache HttpClient。OkHttp 擁有簡潔的 API、高效的性能,并支援多種協定(HTTP/2 和 SPDY)

3)HttpURLConnection

HttpURLConnection 是 Java 的标準類,它繼承自 URLConnection,可用于向指定網站發送 GET 請求、POST 請求。HttpURLConnection 使用比較複雜,不像 HttpClient 那樣容易使用。

4)RestTemplate WebClient

RestTemplate 是 Spring 提供的用于通路 Rest 服務的用戶端,RestTemplate 提供了多種便捷通路遠端 HTTP 服務的方法,能夠大大提高用戶端的編寫效率。

二、feign簡介

1、什麼是Feign

Feign是Netflix開發的聲明式、模闆化的HTTP用戶端,其靈感來自Retrofit、JAXRS-2.0以及WebSocket。Feign可幫助我們更加便捷、優雅地調用HTTP API。

Feign支援多種注解,例如Feign自帶的注解或者JAX-RS注解等。Spring Cloud openfeign對Feign進行了增強,使其支援Spring MVC注解,另外還整合了Ribbon和Eureka,進而使得Feign的使用更加友善。

2、Feign的優勢

Feign可以做到使用 HTTP 請求遠端服務時就像調用本地方法一樣的體驗,開發者完全感覺不到這是遠端方法,更感覺不到這是個 HTTP 請求。它像 Dubbo 一樣,consumer 直接調用接口方法調用 provider,而不需要通過正常的 Http Client 構造請求再解析傳回資料。它解決了讓開發者調用遠端接口就跟調用本地方法一樣,無需關注與遠端的互動細節,更無需關注分布式環境開發。

3、Feign的設計架構

feign簡介與實戰一、JAVA 項目中實作遠端接口調用二、feign簡介三、feign使用四、Spring Cloud Feign的自定義配置及使用

feign底層可基于上述不同的http架構,就是對他們的再封裝。預設底層是httpclient。簡單好用。

三、feign使用

1、單獨使用

1)引入依賴:

<dependency>
    <groupId>com.netflix.feign</groupId>
    <artifactId>feign-core</artifactId>
    <version>8.18.0</version>
</dependency>
<dependency>
    <groupId>com.netflix.feign</groupId>
    <artifactId>feign-jackson</artifactId>
    <version>8.18.0</version>
<dependency>    
           

2)編寫接口:

public interface RemoteService {

    @Headers({"Content-Type: application/json","Accept: application/json"})
    @RequestLine("GET /order/findOrderByUserId/{userId}")
    public R findOrderByUserId(@Param("userId") Integer userId);
}
           

3)使用:

public class FeignDemo {

    public static void main(String[] args) {

        //基于json
        // encoder指定對象編碼方式,decoder指定對象解碼方式
        RemoteService service = Feign.builder()
                .encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder())
                .options(new Request.Options(1000, 3500))
                .retryer(new Retryer.Default(5000, 5000, 3))
                .target(RemoteService.class, "http://localhost:8020/");

        System.out.println(service.findOrderByUserId(1));
    }
}
           

2、Spring Cloud Alibaba整合Feign

1)引入依賴:

<!-- openfeign 遠端調用 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
           

2)編寫調用接口[email protected]注解:

@FeignClient(value = "mall-order", path = "/order")
public interface OrderFeignService {

    @RequestMapping("/findOrderByUserId/{userId}")
    public R findOrderByUserId(@PathVariable("userId") Integer userId);
}
           

3)調用端在啟動類上添加@EnableFeignClients注解:

@SpringBootApplication
@EnableFeignClients
public class MallUserFeignDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(MallUserFeignDemoApplication.class, args);
    }
}
           

4)發起調用,像調用本地方式一樣調用遠端服務:

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    OrderFeignService orderFeignService;

    @RequestMapping(value = "/findOrderByUserId/{id}")
    public R  findOrderByUserId(@PathVariable("id") Integer id) {
        //feign調用
        R result = orderFeignService.findOrderByUserId(id);
        return result;
    }
}
           

四、Spring Cloud Feign的自定義配置及使用

1、日志配置

有時候我們遇到 Bug,比如接口調用失敗、參數沒收到等問題,或者想看看調用性能,就需要配置 Feign 的日志了,以此讓 Feign 把請求資訊輸出來。

1)定義一個配置類,指定日志級别

// 注意: 此處配置@Configuration注解就會全局生效,如果想指定對應微服務生效,就不能配置
public class FeignConfig {
    /**
     * 日志級别
     *
     * @return
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}
           

通過源碼可以看到日志等級有 4 種,分别是:

NONE【性能最佳,适用于生産】:不記錄任何日志(預設值)。

BASIC【适用于生産環境追蹤問題】:僅記錄請求方法、URL、響應狀态代碼以及執行時間。

HEADERS:記錄BASIC級别的基礎上,記錄請求和響應的header。

FULL【比較适用于開發及測試環境定位問題】:記錄請求和響應的header、body和中繼資料。

2)局部配置,讓調用的微服務生效,在@FeignClient 注解中指定使用的配置類

feign簡介與實戰一、JAVA 項目中實作遠端接口調用二、feign簡介三、feign使用四、Spring Cloud Feign的自定義配置及使用

3)修改配置檔案日志等級。格式是"logging.level.feign接口包路徑=debug"

logging:
  level:
    com.jihu.mall.user.feign: debug
           

補充:局部配置可以在yml中配置

feign:
  client:
    config:
      mall-order:  #對應微服務
        loggerLevel: FULL

           

2、契約配置

Spring Cloud 在 Feign 的基礎上做了擴充,可以讓 Feign 支援 Spring MVC 的注解來調用。原生的 Feign 是不支援 Spring MVC 注解的,如果你想在 Spring Cloud 中使用原生的注解方式來定義用戶端也是可以的,通過配置契約來改變這個配置,Spring Cloud 中預設的是 SpringMvcContract。

1)修改契約配置,支援Feign原生的注解

/**
 * 修改契約配置,支援Feign原生的注解
 * @return
 */
@Bean
public Contract feignContract() {
    return new Contract.Default();
}
           

注意:修改契約配置後,OrderFeignService 不再支援springmvc的注解,需要使用Feign原生的注解.

2)OrderFeignService 中配置使用Feign原生的注解

@FeignClient(value = "mall-order", path = "/order")
public interface OrderFeignService {
    @RequestLine("GET /findOrderByUserId/{userId}")
    public R findOrderByUserId(@Param("userId") Integer userId);
}

           

補充,也可以通過yml配置契約

feign:
  client:
    config:
      mall-order:  #對應微服務
        loggerLevel: FULL
        contract: feign.Contract.Default   #指定Feign原生注解契約配置

           

3、通過攔截器實作認證

通常我們調用的接口都是有權限控制的,很多時候可能認證的值是通過參數去傳遞的,還有就是通過請求頭去傳遞認證資訊,比如 Basic 認證方式。 接口鑒權。

A、Feign 中我們可以直接配置 Basic 認證。當然,這種方式我們一般也不會使用,一般都是自己實作攔截器,實作自己的鑒權邏輯。

@Configuration  // 全局配置
public class FeignConfig {
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("admin", "123456");
    }
}

           

B、自定義攔截器實作認證邏輯

1)實作RequestInterceptor接口

public class FeignAuthRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        // 業務邏輯
        String access_token = UUID.randomUUID().toString();
        template.header("Authorization", access_token);
    }
}
           

2)使攔截器生效

@Configuration  // 全局配置
public class FeignConfig {
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
    /**
     * 自定義攔截器
     * @return
     */
    @Bean
    public FeignAuthRequestInterceptor feignAuthRequestInterceptor(){
        return new FeignAuthRequestInterceptor();
    }
}
           

測試結果如下:

feign簡介與實戰一、JAVA 項目中實作遠端接口調用二、feign簡介三、feign使用四、Spring Cloud Feign的自定義配置及使用

補充:可以在yml中配置

feign:
  client:
    config:
      mall-order:  #對應微服務
        requestInterceptors[0]:  #配置攔截器
          com.jihu.mall.user.interceptor.FeignAuthRequestInterceptor

           

mall-order端可以在filter、interceptor中處理添加的資訊。也可以通過@RequestHeader直接擷取資訊

C、适用場景

  • 統一添加 header 資訊;
  • 對 body 中的資訊做修改或替換;

4、逾時時間配置

通過 Options 可以配置連接配接逾時時間和讀取逾時時間,Options 的第一個參數是連接配接的逾時時間(ms),預設值是 2s;第二個是請求處理的逾時時間(ms),預設值是 5s。

@Configuration
public class FeignConfig {
    @Bean
    public Request.Options options() {
        return new Request.Options(5000, 10000);
    }
}
           

補充:yml中配置

feign:
  client:
    config:
      mall-order:  #對應微服務
        # 連接配接逾時時間,預設2s
        connectTimeout: 5000
        # 請求處理逾時時間,預設5s
        readTimeout: 10000
           

補充說明: Feign的底層用的是Ribbon,但逾時時間以Feign配置為準。

測試逾時情況:

feign簡介與實戰一、JAVA 項目中實作遠端接口調用二、feign簡介三、feign使用四、Spring Cloud Feign的自定義配置及使用

傳回結果:

feign簡介與實戰一、JAVA 項目中實作遠端接口調用二、feign簡介三、feign使用四、Spring Cloud Feign的自定義配置及使用

5、GZIP 壓縮配置

開啟壓縮可以有效節約網絡資源,提升接口性能,我們可以配置 GZIP 來壓縮資料:

feign:
  # 配置 GZIP 來壓縮資料
  compression:
    request:
      enabled: true
      # 配置壓縮的類型
      mime-types: text/xml,application/xml,application/json
      # 最小壓縮值
      min-request-size: 2048
    response:
      enabled: true

           

注意:隻有當 Feign 的 Http Client 不是 okhttp3 的時候,壓縮才會生效,配置源碼在FeignAcceptGzipEncodingAutoConfiguration

feign簡介與實戰一、JAVA 項目中實作遠端接口調用二、feign簡介三、feign使用四、Spring Cloud Feign的自定義配置及使用

核心代碼就是 @ConditionalOnMissingBean(type=“okhttp3.OkHttpClient”),表示 Spring BeanFactory 中不包含指定的 bean 時條件比對,也就是沒有啟用 okhttp3 時才會進行壓縮配置。