溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何用SpringCloud的OpenFeign進行服務調用

發(fā)布時間:2022-01-14 14:11:44 來源:億速云 閱讀:137 作者:iii 欄目:開發(fā)技術

本篇內容介紹了“如何用SpringCloud的OpenFeign進行服務調用”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!

前言

Feign是一個聲明式的Web服務客戶端,是面向接口編程的。也就是說使用Feign,只需要創(chuàng)建一個接口并使用注解方式配置它,就可以完成對微服務提供方的接口綁定。

在使用RestTemplate時,每次調用服務都需要指定服務的具體路徑,當在多個地方同時使用時要寫多次,顯得代碼冗余也難以維護,而openfeign就可以避免這種操作。

1、OpenFeign

1.1、OpenFeign概述

1. 是什么?

Feign是一個聲明式的web服務客戶端,讓編寫web服務客戶端變得非常容易,只需創(chuàng)建一個接口并在接口上添加注解即可。

源碼地址

2. 能干嘛?

  • Feign旨在使編寫Java Http客戶端變得更容易。

  • 前面的服務調用在使用Ribbon + RestTemplate時,利用RestTemplate對http請求的封裝處理,形成了一套模板化的調用方法。但是在實際開發(fā)中,由于對服務依賴的調用可能不止一處,往往一個接口會被多處調用,所以通常都會針對每個微服務自行封裝一些客戶端類來包裝這些以來服務的調用。所以,Feign在此基礎上做了進一步封裝,由他來幫助我們定義和實現依賴服務接口的定義。在Feign的實現下,我們只需創(chuàng)建一個接口并使用注解的方式來配置它(以前是Dao接口上面標注Mapper注解,現在是一個微服務接口上面標志一個Feign注解即可),即可完成對服務提供方的接口綁定,簡化了使用Spring Cloud Ribbon時,自動封裝服務調用客戶端的開發(fā)量。

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

3. Feign和OpenFeign的區(qū)別

FeignOpenFeign
Feign是SpringCloud組件中的一個輕量級restful的Http服務客戶端,Feign內置了Ribbon,用來做客戶端負載均衡,去調用服務注冊中心的服務。Feign的使用方式是:使用Feign的注解定義接口,調用這個接口,就可以調用服務注冊中心的服務OpenFeign是SpringCloud在Feign的基礎上支持了SpringMVC的注解,如@RequestMapping等等。OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通過動態(tài)代理的方式實現類,實現類中做負載均衡并調用其他服務

1.2、OpenFeign的使用步驟

1. 建Module

Module的名稱為cloud-consumer-feign-order80。

2. 改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>cloud02</artifactId>
        <groupId>com.xiao</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-consumer-feign-order80</artifactId>

    <!--openfeign-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>com.xiao</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</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>

3. 改YML

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

4. 主啟動

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

@SpringBootApplication
@EnableFeignClients 		//開啟OpenFeign
public class OrderFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignMain80.class,args);
    }
}

@EnableFeignClients開啟OpenFeign

5. PaymentFeignService接口

import com.xiao.cloud.entities.CommonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;


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

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id);
}

@FeignClient(value = "CLOUD-PAYMENT-SERVICE")使用OpenFeign。

6. Controller類

import com.xiao.cloud.entities.CommonResult;
import com.xiao.cloud.entities.Payment;
import com.xiao.cloud.service.PaymentFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class PaymentFeignController {

    @Autowired
    private PaymentFeignService paymentFeignService;


    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        return paymentFeignService.getPaymentById(id);
    }
}

7. 測試結果

如何用SpringCloud的OpenFeign進行服務調用

當我們多次點擊刷新時,端口在8001和8002之間依次變化。

8. 小總結

如何用SpringCloud的OpenFeign進行服務調用

1.3、超時控制

1.3.1、是什么?

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

在yml文件中開啟配置。

1.3.2、修改代碼設置超時錯誤

1. 修改支付模塊8001的Controller

添加以下代碼

    @GetMapping(value = "/payment/feign/timeout")
    public String timeOUt(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ServerPort;
    }

2. 修改訂單模塊的PaymentFeignService

添加以下代碼

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

3. 修改訂單模塊的OrderFeignController

添加以下代碼

    @GetMapping(value = "/consumer/payment/feign/timeout")
    public String timeOUt(){
        return paymentFeignService.timeOUt();
    }

4. 測試結果

如何用SpringCloud的OpenFeign進行服務調用

直接對支付模塊8001的暴露的服務接口進行調用,測驗通過。

如何用SpringCloud的OpenFeign進行服務調用

如果通過訂單模塊進行調用,那么就會報超時錯誤

1.3.3、進行超時配置

在訂單模塊的YML文件中添加以下代碼

ribbon:
  ReadTimeout:  8000
  ConnectTimeout: 8000

1. 測試結果

如何用SpringCloud的OpenFeign進行服務調用

自測通過。

1.4、日志打印

1.4.1、是什么?

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

1.4.2、日志級別
  1. NONE:默認的,不顯示任何日志

  2. BASIC:僅記錄請求方法、URL、響應狀態(tài)碼及執(zhí)行時間

  3. HEADERS:除了BASIC中定義的信息之外,還有請求和響應的頭信息

  4. FULL:除了HEADERS中定義的信息之外,還有請求和響應的正文及元數據。

1.4.3、如何開啟日志打印

1. 編寫日志配置類

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

@Configuration
public class FeignConfig {

    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

2. 在YML文件中進行相關配置

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

ribbon:
  ReadTimeout:  8000
  ConnectTimeout: 8000

logging:
  level:
    com.atguigu.springcloud.service.PaymentFeignService: debug

3. 測試結果

如何用SpringCloud的OpenFeign進行服務調用

4. 包結構圖示

如何用SpringCloud的OpenFeign進行服務調用

“如何用SpringCloud的OpenFeign進行服務調用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI