首先建立一個 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

建立一個啟動類 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 控制檯。

​推薦分散式架構原始碼