【SpringCloud】OpenFeign服務接口調用


OpenFeign服務接口調用

概述

我的理解:
feign
為什么叫偽裝?

Feign可以把Rest的請求進行隱藏,偽裝成類似SpringMVC的Controller一樣。你不用再自己拼接url,拼接參數等等操作,一切都交給Feign去做。

OpenFeign是什么

官網解釋:
https://cloud spring.io/spring -cloud static/Hoxton.SR1/reference/htmlsingle/#spring cloud openfeign

Feign是一個聲明式WebService客戶端。 使用Feign能讓編寫Web Service客戶端更加簡單。
它的使用方法是定義一個服務接口然后在上面添加注解。Feign也支 持可拔插式的編碼器和解碼器。Spring Cloud對Feign進行了封裝,使其支持了Spring MVC標准注解和HttpMessageConverters。 Feign可以與Eureka和Ribbon組合使用以支持負載均衡

Feign是一個聲明式的Web服務客戶端,讓編寫Web服務客戶端變得非常容易,只需#創建一個接口並在接口上添加注解即可

GitHub

https://github.com/spring-cloud/spring-cloud-openfeign

能干嘛

Feign能干什么
Feign旨在使編寫Java Http客戶端變得更容易。
前面在使用Ribbon+ RestTemplate時,利用RestTemplate對http請求的封裝處理,形成了一套模版化的調用方法。 但是在實際開發中,由於對服務依賴的調用可能不止一處, 往往一個接口會被多處調用, 所以通常都會針對每個微服務自行封裝-些客戶端類來包裝這些依賴服務的調用。所以,Feign在此基礎上做了進-步封裝, 由他來幫助我們定義和實現依賴服務接口的定義。在Feign的實現下,我們只需創建一個接口並使用注解的方式來配置它(以前是Dao接口 上面標注Mapper注解,現在是一個微服務接口 上面標注一個Feign注解即可),即可完成對服務提供方的接口綁定,簡化了使用Spring cloud Ribbon時,自動封裝服務調用客戶端的開發量。

Feign集成了Ribbon
利用Ribbon維護了Payment的服務列表信息,並且通過輪詢實現了客戶端的負載均衡。而與Ribbon不同的是,通過feign只需要定義服務綁定接口且以聲明式的方法,優雅而簡單的實現了服務調用

Feign和OpenFeign兩者區別

OpenFeign使用步驟

接口+注解

微服務調用接口+@FeignClient

新建cloud-consumer-feign-order80

Feign在消費端使用

POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2020</artifactId>
        <groupId>com.atguigu.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-consumer-feign-order80</artifactId>
    <description>訂單消費者之feign</description>

    <dependencies>
        <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-common</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--監控-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--熱部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

YML

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

主啟動

@EnableFeignClients

package com.atguigu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @author zzyy
 * @date 2020/02/18 17:20
 **/
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class OrderFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignMain80.class, args);
    }
}

業務類

業務邏輯接口+@FeignClient配置調用provider服務

新建PaymentFeignService接口並新增注解@FeignClient

@FeignClient

@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {

    @GetMapping(value="/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}

控制層Controller

測試

先啟動2個eureka集群7001/7002

再啟動2個微服務8001/8002

啟動OpenFeign

http://localhost/consumer/payment/get/31

Feign自帶負載均衡配置項

小總結

OpenFeign超時控制

超時設置,故意設置超時演示出錯情況

服務提供方8001故意寫暫停程序

@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout() {
    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        return serverPort;
    }
}

服務消費方80添加超時方法PaymentFeignService

@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout();

服務消費方80添加超時方法OrderFeignController

@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeout() {
    //openfeign-ribbon 客戶端默認等待1S
    return  paymentFeignService.paymentFeignTimeout();
}

測試

http://localhost/consumer/payment/feign/timeout

錯誤頁面

OpenFeign默認等待1秒鍾,超過后報錯

是什么

默認Felign客戶端只等待一秒鍾,但是服務端處理需要超過1秒鍾,導致Feign客戶端不想等待了,直接返回報錯。
為了避免這樣的情況,有時候我們需要設置Feign客戶端的超時控制。

yml文件中開啟配置

OpenFeign默認支持Ribbon

YML文件里需要開啟OpenFeign客戶端超時控制

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
# 設置feign客戶端超時時間(OpenFeign默認支持ribbon)
ribbon:
  # 指的是建立連接所用的時間,適用於網絡狀態正常的情況下,兩端連接所用的時間
  ReadTimeout: 5000
  # 指的是建立連接后從服務器讀取到可用資源所用的時間
  ConnectTimeout: 5000

OpenFeign日志打印功能

是什么

Feign提供了日志打印功能,我們可以通過配置來調整日志級別,從而了解Feign中Http請求的細節。
說白了就是對Feign接口的調用情況進行監控和輸出

日志級別

  • NONE:默認的,不顯示任何日志;
  • BASIC:僅記錄請求方法、URL、 響應狀態碼及執行時間;
  • HEADERS:除了BASIC中定義的信息之外,還有請求和響應的頭信息;
  • FULL:除了HEADERS中定義的信息之外,還有請求和響應的正文及元數據。

配置日志bean

package com.atguigu.springcloud.config;

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

/**
 * OpenFeignClient配置
 *
 * @author zzyy
 * @create 2020/3/6 18:02
 **/
@Configuration
public class FeignConfig {

    /**
     * feignClient配置日志級別
     *
     * @return
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        // 請求和響應的頭信息,請求和響應的正文及元數據
        return Logger.Level.FULL;
    }
}

YML文件里需要開啟日志的Feign客戶端

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
# 設置feign客戶端超時時間(OpenFeign默認支持ribbon)
ribbon:
  # 指的是建立連接所用的時間,適用於網絡狀態正常的情況下,兩端連接所用的時間
  ReadTimeout: 5000
  # 指的是建立連接后從服務器讀取到可用資源所用的時間
  ConnectTimeout: 5000
logging:
  level:
    # feign日志以什么級別監控哪個接口
    com.atguigu.springcloud.service.PaymentFeignService: debug

后台日志查看


免責聲明!

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



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