Spring Cloud Feign的兩種使用姿勢

Profile


概述

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

注: 本文首發於  博客 CodeSheep · 程序羊,歡迎光臨 小站

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


創建基於 Eureka的服務註冊中心

三個步驟即可搞定:

  • 建工程

創建一個名爲 eureka_server的 SpringBoot工程,並在pom.xml中添加好對應依賴

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

修改應用主類,添加 @EnableEurekaServer註解

@EnableEurekaServer@SpringBootApplicationpublic 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#默認設置下,服務註冊中心自己也會將自己作爲客戶端來嘗試註冊它自己,所以我們需要禁用它的客戶端註冊行爲eureka.client.register-with-eureka=falseeureka.client.fetch-registry=false
  • 啓動服務註冊中心

瀏覽器訪問之:

瀏覽器訪問服務註冊中心

此時還沒有任何服務註冊上來。


創建服務提供者

  • 建工程

創建一個名爲 service_provider的 SpringBoot工程,並在pom.xml中添加好對應依賴:

    <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@SpringBootApplicationpublic class ServiceProviderApplication {    public static void main(String[] args) {
        SpringApplication.run(ServiceProviderApplication.class, args);
    }
}
  • 添加控制器 DateServiceController

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

@RestControllerpublic 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=1112eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
  • 啓動工程

瀏覽器訪問服務註冊中心,我們發現服務提供者 service_provider已經註冊到 eureka_server上:

服務提供者已註冊上來了

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

測試發現服務提供者的接口工作正常

接下來我們創建服務消費者,是 Feign該登場的時候了!


創建基於 Feign的服務消費者

  • 創建一個名爲 service_consumer的 SpringBoot工程,並在pom.xml中添加好對應依賴

    <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>
  • 修改應用主類

主要是添加有關 Feign客戶端的一些註解而已

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

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

@FeignClient( value = "service-provider" )public interface DateServiceFeignClientInterface {    @GetMapping("/test")    String consumer( @RequestParam("param") String param );
}
  • 創建控制器:DateServiceFeignController

注意,這是服務消費者提供的 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=1113eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
  • 啓動服務消費者

我們先去服務註冊中心上看看,發現 服務消費者也註冊上來了:

服務消費者已註冊上來

然後我們瀏覽器訪問 服務消費者提供的Rest接口: http://localhost:1113/consumer/date?param=www.codesheep.cn

數據成功取回

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

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

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


抽象出一個公共的 API服務

  • 創建一個普通 Maven項目:service_provider_api

  • 創建一個公共接口:DateService

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

改造之前的 服務提供者 / 消費者項目

  • 在服務消費者 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 );
    }
}
  • 在服務提供者 service_provider項目中來實現我們在公共api項目 service_provider_api中的 DateService接口,賦予實際邏輯

@RestControllerpublic 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_providerservice_consumer 三個項目分別啓動

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

成功實現服務調用

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




說到這裏,也給大家推薦一個架構交流學習羣:828545509,裏面會分享一些資深架構師錄製的視頻錄像:有Spring,MyBatis,Netty源碼分析

,高併發、高性能、分佈式、微服務架構的原理,JVM性能優化這些成爲架構師必備的知識體系。還能領取免費的學習資源,相信對於已經工作

和遇到技術瓶頸的碼友,在這個羣裏會有你需要的內容。


點擊鏈接加入羣聊【Java高級架構師學習羣】:https://jq.qq.com/?_wv=1027&k=5T2kMGl


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章