Spring Cloud構建微服務架構:服務註冊與發現(Eureka、Consul)【Dalston版】

已經有很是長的時間沒有更新《Spring Cloud構建微服務架構》系列文章了,自從開始寫Spring Cloud的專題內容開始就得到了很多的閱讀量和承認,固然也有一些批評,其中也不乏一些很中肯的意見和深度的問題,對我來講也是進一步提升的契機,在此感謝全部關注我博客的讀者們。java

因爲以前主要精力都花在的編寫《Spring Cloud微服務實戰》一書上,因此該系列文章就沒有獲得持續的維護和更新。因爲漫長的寫書過程和繁瑣的出版流程,在本書一面世的時候,在版本上已經落後於當前的最新版本。雖然在書中前先後後加入了一些版本更新的注意事項,可是認識過程不是一蹴而就的,老是隨着實踐的深刻慢慢發現的。因此,決定重寫一下該系列文章,一方面將Spring Cloud的版本更新到Dalston,另外一方面從新組織內容並增長一些以前沒有寫過的重要組件。但願經過這個系列,來幫助準備使用Spring Cloud的朋友們快速入門。同時,也是做爲《Spring Cloud微服務實戰》一書對最新版本作一些不一樣內容的補充。git

Spring Cloud簡介

Spring Cloud是一個基於Spring Boot實現的雲應用開發工具,它爲基於JVM的雲應用開發中涉及的配置管理、服務發現、斷路器、智能路由、微代理、控制總線、全局鎖、決策競選、分佈式會話和集羣狀態管理等操做提供了一種簡單的開發方式。github

Spring Cloud包含了多個子項目(針對分佈式系統中涉及的多個不一樣開源產品),好比:Spring Cloud Config、Spring Cloud Netflix、Spring Cloud0 CloudFoundry、Spring Cloud AWS、Spring Cloud Security、Spring Cloud Commons、Spring Cloud Zookeeper、Spring Cloud CLI等項目。web

微服務架構

「微服務架構」在這幾年很是的火熱,以致於關於微服務架構相關的開源產品被反覆的說起(好比:netflix、dubbo),Spring Cloud也因Spring社區的強大知名度和影響力也被廣大架構師與開發者備受關注。spring

那麼什麼是「微服務架構」呢?簡單的說,微服務架構就是將一個完整的應用從數據存儲開始垂直拆分紅多個不一樣的服務,每一個服務都能獨立部署、獨立維護、獨立擴展,服務與服務間經過諸如RESTful API的方式互相調用。json

對於「微服務架構」,你們在互聯網能夠搜索到不少相關的介紹和研究文章來進行學習和了解。也能夠閱讀始祖Martin Fowler的《Microservices》(中文版翻譯點擊查看),本文不作更多的介紹和描述。bootstrap

服務治理

在簡單介紹了Spring Cloud和微服務架構以後,下面迴歸本文的主旨內容,如何使用Spring Cloud來實現服務治理。bash

因爲Spring Cloud爲服務治理作了一層抽象接口,因此在Spring Cloud應用中能夠支持多種不一樣的服務治理框架,好比:Netflix Eureka、Consul、Zookeeper。在Spring Cloud服務治理抽象層的做用下,咱們能夠無縫地切換服務治理實現,而且不影響任何其餘的服務註冊、服務發現、服務調用等邏輯。架構

因此,下面咱們經過介紹兩種服務治理的實現來體會Spring Cloud這一層抽象所帶來的好處。app

Spring Cloud Eureka

首先,咱們來嘗試使用Spring Cloud Eureka來實現服務治理。

Spring Cloud Eureka是Spring Cloud Netflix項目下的服務治理模塊。而Spring Cloud Netflix項目是Spring Cloud的子項目之一,主要內容是對Netflix公司一系列開源產品的包裝,它爲Spring Boot應用提供了自配置的Netflix OSS整合。經過一些簡單的註解,開發者就能夠快速的在應用中配置一下經常使用模塊並構建龐大的分佈式系統。它主要提供的模塊包括:服務發現(Eureka),斷路器(Hystrix),智能路由(Zuul),客戶端負載均衡(Ribbon)等。

下面,就來具體看看如何使用Spring Cloud Eureka實現服務治理。

建立「服務註冊中心」

建立一個基礎的Spring Boot工程,命名爲eureka-server,並在pom.xml中引入須要的依賴內容:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-dependencies</artifactId>
           <version>Dalston.SR1</version>
           <type>pom</type>
           <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

經過@EnableEurekaServer註解啓動一個服務註冊中心提供給其餘應用進行對話。這一步很是的簡單,只須要在一個普通的Spring Boot應用中添加這個註解就能開啓此功能,好比下面的例子:

@EnableEurekaServer
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class)
                    .web(true).run(args);
    }
}

在默認設置下,該服務註冊中心也會將本身做爲客戶端來嘗試註冊它本身,因此咱們須要禁用它的客戶端註冊行爲,只須要在application.properties配置文件中增長以下信息:

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

eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

爲了與後續要進行註冊的服務區分,這裏將服務註冊中心的端口經過server.port屬性設置爲1001。啓動工程後,訪問:http://localhost:1001/,能夠看到下面的頁面,其中尚未發現任何服務。

建立「服務提供方」

下面咱們建立提供服務的客戶端,並向服務註冊中心註冊本身。本文咱們主要介紹服務的註冊與發現,因此咱們不妨在服務提供方中嘗試着提供一個接口來獲取當前全部的服務信息。

首先,建立一個基本的Spring Boot應用。命名爲eureka-client,在pom.xml中,加入以下配置:

<parent> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

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

<dependencyManagement>
    <dependencies>
        <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-dependencies</artifactId>
           <version>Dalston.SR1</version>
           <type>pom</type>
           <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

其次,實現/dc請求處理接口,經過DiscoveryClient對象,在日誌中打印出服務實例的相關內容。

@RestController
public class DcController {

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("/dc")
    public String dc() {
        String services = "Services: " + discoveryClient.getServices();
        System.out.println(services);
        return services;
    }

}

最後在應用主類中經過加上@EnableDiscoveryClient註解,該註解能激活Eureka中的DiscoveryClient實現,這樣才能實現Controller中對服務信息的輸出。

@EnableDiscoveryClient
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        new SpringApplicationBuilder(
            ComputeServiceApplication.class)
            .web(true).run(args);
    }
}

咱們在完成了服務內容的實現以後,再繼續對application.properties作一些配置工做,具體以下:

spring.application.name=eureka-client
server.port=2001
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/

經過spring.application.name屬性,咱們能夠指定微服務的名稱後續在調用的時候只須要使用該名稱就能夠進行服務的訪問。eureka.client.serviceUrl.defaultZone屬性對應服務註冊中心的配置內容,指定服務註冊中心的位置。爲了在本機上測試區分服務提供方和服務註冊中心,使用server.port屬性設置不一樣的端口。

啓動該工程後,再次訪問:http://localhost:1001/。能夠以下圖內容,咱們定義的服務被成功註冊了。

固然,咱們也能夠經過直接訪問eureka-client服務提供的/dc接口來獲取當前的服務清單,只須要訪問:http://localhost:2001/dc,咱們能夠獲得以下輸出返回:

Services: [eureka-client]

其中,方括號中的eureka-client就是經過Spring Cloud定義的DiscoveryClient接口在eureka的實現中獲取到的全部服務清單。因爲Spring Cloud在服務發現這一層作了很是好的抽象,因此,對於上面的程序,咱們能夠無縫的從eureka的服務治理體系切換到consul的服務治理體系中區。

Spring Cloud Consul

Spring Cloud Consul項目是針對Consul的服務治理實現。Consul是一個分佈式高可用的系統,它包含多個組件,可是做爲一個總體,在微服務架構中爲咱們的基礎設施提供服務發現和服務配置的工具。它包含了下面幾個特性:

  • 服務發現

  • 健康檢查

  • Key/Value存儲

  • 多數據中心

因爲Spring Cloud Consul項目的實現,咱們能夠輕鬆的將基於Spring Boot的微服務應用註冊到Consul上,並經過此實現微服務架構中的服務治理。

以以前實現的基於Eureka的示例(eureka-client)爲基礎,咱們如何將以前實現的服務提供者註冊到Consul上呢?方法很是簡單,咱們只須要在pom.xml中將eureka的依賴修改成以下依賴:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>

接下來再修改一下application.properites,將consul須要的配置信息加入便可,好比:(下面配置是默認值)

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500

到此爲止,咱們將eureka-client轉換爲基於consul服務治理的服務提供者就完成了。前文咱們已經有提到過服務發現的接口DiscoveryClient是Spring Cloud對服務治理作的一層抽象,因此能夠屏蔽Eureka和Consul服務治理的實現細節,咱們的程序不須要作任何改變,只須要引入不一樣的服務治理依賴,並配置相關的配置屬性就能輕鬆的將微服務歸入Spring Cloud的各個服務治理框架中。

下面能夠嘗試讓consul的服務提供者運行起來。這裏可能讀者會問,不須要建立相似eureka-server的服務端嗎?因爲Consul自身提供了服務端,因此咱們不須要像以前實現Eureka的時候建立服務註冊中心,直接經過下載consul的服務端程序就可使用。

咱們能夠用下面的命令啓動consul的開發模式:

$consul agent -dev
==> Starting Consul agent...
==> Starting Consul agent RPC...
==> Consul agent running!
           Version: 'v0.7.2'
         Node name: 'Lenovo-zhaiyc'
        Datacenter: 'dc1'
            Server: true (bootstrap: false)
       Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400)
      Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
    Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false
             Atlas: <disabled>

==> Log data will now stream in as it occurs:

    2017/06/22 07:50:54 [INFO] raft: Initial configuration (index=1): [{Suffrage:Voter ID:127.0.0.1:8300 Address:127.0.0.1:8300}]
    2017/06/22 07:50:54 [INFO] raft: Node at 127.0.0.1:8300 [Follower] entering Follower state (Leader: "")
    2017/06/22 07:50:54 [INFO] serf: EventMemberJoin: Lenovo-zhaiyc 127.0.0.1
    2017/06/22 07:50:54 [INFO] consul: Adding LAN server Lenovo-zhaiyc (Addr: tcp/127.0.0.1:8300) (DC: dc1)
    2017/06/22 07:50:54 [INFO] serf: EventMemberJoin: Lenovo-zhaiyc.dc1 127.0.0.1
    2017/06/22 07:50:54 [INFO] consul: Adding WAN server Lenovo-zhaiyc.dc1 (Addr: tcp/127.0.0.1:8300) (DC: dc1)
    2017/06/22 07:51:01 [ERR] agent: failed to sync remote state: No cluster leader
    2017/06/22 07:51:02 [WARN] raft: Heartbeat timeout from "" reached, starting election
    2017/06/22 07:51:02 [INFO] raft: Node at 127.0.0.1:8300 [Candidate] entering Candidate state in term 2
    2017/06/22 07:51:02 [DEBUG] raft: Votes needed: 1
    2017/06/22 07:51:02 [DEBUG] raft: Vote granted from 127.0.0.1:8300 in term 2. Tally: 1
    2017/06/22 07:51:02 [INFO] raft: Election won. Tally: 1
    2017/06/22 07:51:02 [INFO] raft: Node at 127.0.0.1:8300 [Leader] entering Leader state
    2017/06/22 07:51:02 [INFO] consul: cluster leadership acquired
    2017/06/22 07:51:02 [INFO] consul: New leader elected: Lenovo-zhaiyc
    2017/06/22 07:51:02 [DEBUG] consul: reset tombstone GC to index 3
    2017/06/22 07:51:02 [INFO] consul: member 'Lenovo-zhaiyc' joined, marking health alive
    2017/06/22 07:51:02 [INFO] agent: Synced service 'consul'
    2017/06/22 07:51:02 [DEBUG] agent: Node info in sync

consul服務端啓動完成以後,咱們再將以前改造後的consul服務提供者啓動起來。consul與eureka同樣,都提供了簡單的ui界面來查看服務的註冊狀況:

更多關於Consul的使用指南,讀者可查看官方文檔:https://www.consul.io/

更多Spring Cloud內容請持續關注個人博客更新或在《Spring Cloud微服務實戰》中獲取。

代碼示例

樣例工程將沿用以前在碼雲和GitHub上建立的SpringCloud-Learning項目,從新作了一下整理。經過不一樣目錄來區分Brixton和Dalston的示例。

具體工程說明以下:

  • eureka的服務註冊中心:eureka-server

  • eureka的服務提供方:eureka-client

  • consul的服務提供方:consul-client

相關閱讀

相關文章
相關標籤/搜索