服務註冊發現Eureka之一:Spring Cloud Eureka的服務註冊與發現

Spring Cloud簡介

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

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

微服務架構

"微服務架構」在這幾年非常的火熱,以至於關於微服務架構相關的產品社區也變得越來越活躍(比如:netflix、dubbo),Spring Cloud也因Spring社區的強大知名度和影響力也被廣大架構師與開發者備受關注。

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

對於「微服務架構」,大家在互聯網可以搜索到很多相關的介紹和研究文章來進行學習和了解。也可以閱讀始祖Martin Fowler的《Microservices》,本文不做更多的介紹和描述。

服務註冊與發現

在簡單介紹了Spring Cloud和微服務架構之後,下面迴歸本文的主旨內容,如何使用Spring Cloud搭建服務註冊與發現模塊。

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

所以,我們這裏的核心內容就是服務發現模塊:Eureka。下面我們動手來做一些嘗試。

創建「服務註冊中心」

創建一個基礎的Spring Boot工程springcloud,並在pom.xml中引入需要的依賴內容:

<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>
    <groupId>com.dxz</groupId>
    <artifactId>springcloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>   <!--配合spring cloud版本 -->
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <!--設置字符編碼及java版本 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--增加eureka-server的依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
        <!--用於測試的,本例可省略 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!--依賴管理,用於管理spring-cloud的依賴 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-parent</artifactId>
                <version>Brixton.SR3</version>   <!--官網爲Angel.SR4版本,但是我使用的時候總是報錯 -->
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <!--使用該插件打包 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

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

package springcloud.main;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

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

在默認設置下,該服務註冊中心也會將自己作爲客戶端來嘗試註冊它自己,所以我們需要禁用它的客戶端註冊行爲,只需要在src/main/resources/application.properties中增加如下配置:

server.port=1111
eureka.client.register-with-eureka=false 
eureka.client.fetch-registry=false 
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka

爲了與後續要進行註冊的服務區分,這裏將服務註冊中心的端口通過server.port屬性設置爲1111。

啓動工程後,訪問:http://localhost:1111/

可以看到下面的頁面,其中還沒有發現任何服務

創建「服務提供方」

下面我們創建提供服務的客戶端,並向服務註冊中心註冊自己。

假設我們有一個提供計算功能的微服務模塊,我們實現一個RESTful API,通過傳入兩個參數a和b,最後返回a + b的結果。

新建一個工程springcloud-compute

首先,創建一個基本的Spring Boot應用,在pom.xml中,加入如下配置:

<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>
    <groupId>com.dxz</groupId>
    <artifactId>springcloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>   <!--配合spring cloud版本 -->
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <!--設置字符編碼及java版本 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--增加eureka-server的依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
        <!--用於測試的,本例可省略 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!--依賴管理,用於管理spring-cloud的依賴 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-parent</artifactId>
                <version>Brixton.SR3</version>   <!--官網爲Angel.SR4版本,但是我使用的時候總是報錯 -->
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <!--使用該插件打包 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

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

package springcloud.main;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ComputeController {
    private final Logger logger = Logger.getLogger(getClass());
    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
        ServiceInstance instance = client.getLocalServiceInstance();
        Integer r = a + b;
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return r;
    }
}

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

package springcloud.main;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

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

我們在完成了服務內容的實現之後,再繼續對springcloud-compute/src/main/resources/application.properties做一些配置工作,具體如下:

spring.application.name=compute-service
server.port=2223
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

通過spring.application.name屬性,我們可以指定微服務的名稱後續在調用的時候只需要使用該名稱就可以進行服務的訪問。

eureka.client.serviceUrl.defaultZone屬性對應服務註冊中心的配置內容,指定服務註冊中心的位置。

爲了在本機上測試區分服務提供方和服務註冊中心,使用server.port屬性設置不同的端口。

啓動該工程後,再次訪問:http://localhost:1111/

可以看到,我們定義的服務被註冊了。