[SpringCloud教程]6. OpenFeign遠程接口調用


OpenFeign是聲明式方式定義Web服務的客戶端(說白了就是將原有的url請求調用轉化為本地方法調用一樣方便快捷),並可通過集成Ribbon或Eureka實現負載均衡。

集成

  • 在SpringCloud案例項目里建立新模塊 ms-consumer-eureka-openfeign,並在父pom里聲明,該模塊pom.xml如下
<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.spz.demo</groupId>
        <artifactId>spring-cloud-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>ms-consumer-eureka-openfeign</artifactId>
    <packaging>jar</packaging>

    <description>消費者模塊 - 使用Eureka注冊中心 - 使用OpenFeign客戶端</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-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>com.spz.demo</groupId>
            <artifactId>api-common</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>
  • application.properties 配置如下
server.port=7001

# Eureka
eureka.client.register-with-eureka=false
eureka.client.service-url.defaultZone=http://eureka6001:6001/eureka,http://eureka6002:6002/eureka,http://eureka6003:6003/eureka

# Feign 日志級別
logging.level.com.spz.demo.scloud.consumer.openfeign.service.IEurekaProviderService=debug

# Feign 超時配置
openfeign.connectTimeoutMs=1000
openfeign.readTimeoutMs=5000
  • 配置類OpenFeignConfiguration.java
package com.spz.demo.scloud.consumer.openfeign.config;

import com.netflix.ribbon.Ribbon;
import feign.Logger;
import feign.Request;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * OpenFeign 配置
 * @author spzmmd
 * @createTime 2021/04/12
 */
@Configuration
public class OpenFeignConfiguration {

    /**
     * 連接超時
     * 單位: ms
     */
    @Value("${openfeign.connectTimeoutMs}")
    private int connectTimeoutMs;

    /**
     * 讀取超時
     * 單位: ms
     */
    @Value("${openfeign.readTimeoutMs}")
    private int readTimeoutMs;

    /**
     * 配置超時時間
     * @return
     */
    @Bean
    public Request.Options options() {
        return new Request.Options(connectTimeoutMs, readTimeoutMs);
    }

    /**
     * 配置OpenFeign輸出什么日志, 方便調試
     * @return
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}
  • 啟動類 ConsumerOpenFeignApp.java
package com.spz.demo.scloud.consumer.openfeign;

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

@EnableFeignClients
@SpringBootApplication
public class ConsumerOpenFeignApp {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerOpenFeignApp.class, args);
    }
}
  • 通過OpenFeign來實現微服務接口調用的方法是,將接口調用聲明為一個個接口方法,如下代碼
package com.spz.demo.scloud.consumer.openfeign.service;

import com.spz.demo.scloud.common.core.bean.RestBean;
import com.spz.demo.scloud.consumer.openfeign.config.OpenFeignConfiguration;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * Eureka 服務提供者 接口
 * 用於配置 Feign 接口
 * @author spzmmd
 * @createTime 2021/04/12
 */
@Component
@FeignClient(value = "MS-PROVIDER", configuration = OpenFeignConfiguration.class)
public interface IEurekaProviderService {

    @GetMapping(value = "/projectInfo")
    public RestBean projectInfo();

}
  • 測試用的控制器
package com.spz.demo.scloud.consumer.openfeign.controller;

import com.spz.demo.scloud.common.core.bean.RestBean;
import com.spz.demo.scloud.common.service.AppService;
import com.spz.demo.scloud.consumer.openfeign.service.IEurekaProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 測試 openFeign
 * @author spzmmd
 * @createTime 2021/04/12
 */
@RestController
@RequestMapping("/openFeign")
public class OpenFeignTestController {

    // 使用OpenFeign,實現以接口調用的方式來進行網絡請求
    @Autowired
    private IEurekaProviderService eurekaProviderService;

    /**
     * 服務遠程調用測試 - 使用 openFeign
     * @return
     */
    @RequestMapping("/projectInfo")
    public RestBean appServiceProjectInfo(){
        RestBean restBean = eurekaProviderService.projectInfo();
        return restBean;
    }
}
  • 運行時,需要啟動eureka-server(用於服務注冊發現) 和兩個ms-provider節點,用於測試OpenFeign方式調用微服務接口,而后啟動ms-consumer-eureka-openfeign模塊,不斷訪問如下地址:
http://localhost:7001/openFeign/projectInfo

正常應該分別返回兩個服務的端口號(OpenFeign默認支持負載均衡)

{
  "code": 2000,
  "message": "MS-PROVIDER:8001: (基於Eureka注冊中心)",
  "data": null
}

{
  "code": 2000,
  "message": "MS-PROVIDER:8002: (基於Eureka注冊中心)",
  "data": null
}

交流&聯系

  • QQ群
    歡迎加入Java交流群(qq群號: 776241689 )

  • 歡迎關注公眾號"后端技術學習分享"獲取更多技術文章!
    PS:小到Java后端技術、計算機基礎知識,大到微服務、Service Mesh、大數據等,都是本人研究的方向。我將定期在公眾號中分享技術干貨,希望以我一己之力,拋磚引玉,幫助朋友們提升技術能力,共同進步!
    在這里插入圖片描述

  • 博客

原創不易,轉載請在開頭著名文章來源和作者。如果我的文章對您有幫助,請點贊/收藏/關注鼓勵支持一下吧❤❤❤❤❤❤


免責聲明!

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



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