OpenFeign 服務接口調用


一、概述

1、是什么

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

2、能干什么

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

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

Feign 集成了 Ribbon

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

3、Feign和OpenFeign兩者區別

二、OpenFeign使用步驟

1)新建cloud-consumer-feign-order80,Feign在消費端使用

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>cloud2020</artifactId>
        <groupId>com.atguigu.springcloud</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.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>
pom文件

3)改YML文件

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

4)啟動類

package com.atguigu.springcloud;

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

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

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

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

package com.atguigu.springcloud.service;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import feign.Param;
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") public interface PaymentFeignService {

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

6)控制層Controller

package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentFeignService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class OrderFeignController {

    @Resource
    private PaymentFeignService paymentFeignService;

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

7)測試

  • 先啟動2個eureka集群7001/7002
  • 再啟動2個微服務8001/8002
  • 啟動OpenFeign啟動
  • http://localhost/consumer/payment/get/31
  • Feign自帶負載均衡配置項

8)小總結

三、OpenFeign超時控制

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

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

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

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

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

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

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

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

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

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

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:  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;

@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

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

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eureka
ribbon:
  ReadTimeout:  5000
  ConnectTimeout: 5000 logging: level: com.atguigu.springcloud.service.PaymentFeignService: debug

 


免責聲明!

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



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