(九) 跟我學習SpringCloud-搭建Eureka服務註冊中心

首先創建一個 Maven 項目,取名爲 eureka-server,在 pom.xml 中配置 Eureka 的依賴信息,代碼如下所示。

<!-- Spring Boot -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.6.RELEASE</version>
    <relativePath />
</parent>

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

<!-- Spring Cloud -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley.SR2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

創建一個啓動類 EurekaServerApplication,代碼如下所示。

@EnableEurekaServer
@SpringBootApplication
    public static void main(String[] args) {
        SpringApplication.run(EurekaServer Application.class, args);
    }
}

這裏所說的啓動類,跟我們之前講的 Spring Boot 幾乎完全一樣,只是多了一個 @EnableEurekaServer 註解,表示開啓 Eureka Server。

接下來在 src/main/resources 下面創建一個 application.properties 屬性文件,增加下面的配置:

spring.application.name=eureka-server
server.port=8761
# 由於該應用爲註冊中心, 所以設置爲false, 代表不向註冊中心註冊自己
eureka.client.register-with-eureka=false
# 由於註冊中心的職責就是維護服務實例, 它並不需要去檢索服務, 所以也設置爲 false
eureka.client.fetch-registry=false

eureka.client.register-with-eureka 一定要配置爲 false,不然啓動時會把自己當作客戶端向自己註冊,會報錯。

接下來直接運行 EurekaServerApplication 就可以啓動我們的註冊中心服務了。我們在 application.properties 配置的端口是 8761,則可以直接通http://localhost:8761/ 去瀏覽器中訪問,然後便會看到 Eureka 提供的 Web 控制檯。

推薦分佈式架構源碼

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