Spring Cloud Feign的兩種使用姿勢

Profile

概述

最近結(jié)合一些別人的開源項目來學(xué)習Spring Cloud,其中關(guān)于服務(wù)消費這方面的一個很便利的工具 Feign讓我記憶頗深。雖然網(wǎng)上的Demo和例子不勝枚舉,但大多比較分散,本文就來集中記錄一下聲明式客戶端 Feign的一些使用姿勢。

注: 本文首發(fā)于 博客 CodeSheep · 程序羊,歡迎光臨 小站!

下文就結(jié)合例子來記錄這一過程,代碼在文尾處。


創(chuàng)建基于 Eureka的服務(wù)注冊中心

三個步驟即可搞定:

  • 建工程

創(chuàng)建一個名為 eureka_server的 SpringBoot工程,并在pom.xml中添加好對應(yīng)依賴

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
  • 改主類

修改應(yīng)用主類,添加 @EnableEurekaServer注解

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
  • 加配置

配置 application.properties 文件如下所示:

spring.application.name=eureka-server
server.port=1111

eureka.instance.hostname=localhost

#默認設(shè)置下,服務(wù)注冊中心自己也會將自己作為客戶端來嘗試注冊它自己,所以我們需要禁用它的客戶端注冊行為
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
  • 啟動服務(wù)注冊中心

瀏覽器訪問之:

瀏覽器訪問服務(wù)注冊中心

此時還沒有任何服務(wù)注冊上來。


創(chuàng)建服務(wù)提供者

  • 建工程

創(chuàng)建一個名為 service_provider的 SpringBoot工程,并在pom.xml中添加好對應(yīng)依賴:

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
  • 改主類

添加 @EnableDiscoveryClient注解

@EnableDiscoveryClient
@SpringBootApplication
public class ServiceProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceProviderApplication.class, args);
    }
}
  • 添加控制器 DateServiceController

提供一個Restful接口而已,該接口的作用是獲取服務(wù)器上的時間并返回

@RestController
public class DateServiceController {

    @RequestMapping( value = "/test", method = RequestMethod.GET )
    public String test( @RequestParam String param ){
        return "hello " + param;
    }
}
  • 配置 application.properties文件
spring.application.name=service_provider
server.port=1112
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
  • 啟動工程

瀏覽器訪問服務(wù)注冊中心,我們發(fā)現(xiàn)服務(wù)提供者 service_provider已經(jīng)注冊到 eureka_server上:

服務(wù)提供者已注冊上來了

同時瀏覽器訪問:http://localhost:1112/test?param=www.codesheep.cn,可以測試服務(wù)提供 service_provider提供的接口工作正常

測試發(fā)現(xiàn)服務(wù)提供者的接口工作正常

接下來我們創(chuàng)建服務(wù)消費者,是 Feign該登場的時候了!


創(chuàng)建基于 Feign的服務(wù)消費者

  • 創(chuàng)建一個名為 service_consumer的 SpringBoot工程,并在pom.xml中添加好對應(yīng)依賴
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  • 修改應(yīng)用主類

主要是添加有關(guān) Feign客戶端的一些注解而已

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceConsumerApplication.class, args);
    }
}
  • 創(chuàng)建一個 Feign客戶端的接口:DateServiceFeignClientInterface

很明顯其內(nèi)部用 @FeignClient( value = "service-provider" ) 聲明的方式指向了 服務(wù)提供者,而接口方法則實現(xiàn)了對 服務(wù)提供者接口的實際調(diào)用

@FeignClient( value = "service-provider" )
public interface DateServiceFeignClientInterface {

    @GetMapping("/test")
    String consumer( @RequestParam("param") String param );
}
  • 創(chuàng)建控制器:DateServiceFeignController

注意,這是服務(wù)消費者提供的 Rest接口

@RestController
@RequestMapping("/consumer")
public class DateServiceFeignController {

    @Resource
    DateServiceFeignClientInterface dateServiceFeignClientInterface;

    @GetMapping("/date")
    public String getDate( @RequestParam String param ) {
        return dateServiceFeignClientInterface.consumer( param );
    }
}
  • 配置 application.properties
spring.application.name=service-consumer
server.port=1113

eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
  • 啟動服務(wù)消費者

我們先去服務(wù)注冊中心上看看,發(fā)現(xiàn) 服務(wù)消費者也注冊上來了:

服務(wù)消費者已注冊上來

然后我們?yōu)g覽器訪問 服務(wù)消費者提供的Rest接口: http://localhost:1113/consumer/date?param=www.codesheep.cn

數(shù)據(jù)成功取回

這樣我們就通過 服務(wù)消費者的 Feign客戶端 取到了服務(wù)提供者 給予的接口數(shù)據(jù)。

上面這就是聲明式客戶端 Feign的第一種使用姿勢,也是常用的手法,常見于很多Demo

下面我們來實踐一下關(guān)于 Feign的繼承與實現(xiàn)機制,發(fā)現(xiàn)其使用更加靈活( Feign支持接口繼承方式快速生成客戶端,頗有點RPC的意思(關(guān)于RPC的實踐可以參考我的文章:《RPC框架實踐之:Google gRPC》、《RPC框架實踐之:Apache Thrift》) )


抽象出一個公共的 API服務(wù)

  • 創(chuàng)建一個普通 Maven項目:service_provider_api

  • 創(chuàng)建一個公共接口:DateService

public interface DateService {
    @GetMapping("/api/test")
    String consumer( @RequestParam("param") String param );
}

改造之前的 服務(wù)提供者 / 消費者項目

  • 在服務(wù)消費者 service_consumer項目中添加一個新的Feign的客戶端接口
@FeignClient( value = "service-provider" )
public interface DateServiceFeignClientInterface2 extends DateService {
}
  • 并且在 service_consumer項目中添加一個新的控制器 DateServiceFeignController2
@RestController
@RequestMapping("/consumer2")
public class DateServiceFeignController2 {

    @Resource
    DateServiceFeignClientInterface2 dateServiceFeignClientInterface2;

    @GetMapping("/date")
    public String getDate( @RequestParam String param ) {
        return dateServiceFeignClientInterface2.consumer( param );
    }
}
  • 在服務(wù)提供者 service_provider項目中來實現(xiàn)我們在公共api項目 service_provider_api中的 DateService接口,賦予實際邏輯
@RestController
public class DateServiceController2 implements DateService {

    @Override
    public String consumer( @RequestParam String param) {
        Date now = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("今天是"+"yyyy年MM月dd日 E kk點mm分" );
        String nowTime = simpleDateFormat.format( now );
        return "hello again " + param + ", " + nowTime;
    }
}
  • 依次將 eureka_serverservice_provider、service_consumer 三個項目分別啟動

瀏覽器訪問:http://localhost:1113/consumer2/date?param=www.codesheep.cn

成功實現(xiàn)服務(wù)調(diào)用

使用 feign的繼承特性時,可以將服務(wù)接口的定義從服務(wù)消費者中剝離出去,形成獨立的api項目從而可以很方便的實現(xiàn)接口定義和依賴的共享,不用再復(fù)制粘貼接口進行綁定,當然這種做法存在的問題就是可能會導(dǎo)致服務(wù)提供者和服務(wù)消費者間的耦合度增高,此時如果服務(wù)提供者修改了一個接口定義,服務(wù)消費者可能也得跟著變,進而帶來一些坑。



后 記

由于能力有限,若有錯誤或者不當之處,還請大家批評指正,一起學(xué)習交流!

本文實驗代碼在此



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容