1. 程式人生 > >SpringCloud微服務之快速搭建EurekaServer

SpringCloud微服務之快速搭建EurekaServer

SpringCloud微服務系列部落格:

Spring Cloud Eureka可以快速實現服務註冊與發現,這在微服務專案中非常有意義。

接下來配合IntelliJ使用Spring Cloud框架+maven來從頭搭建一個Eureka Server工程:

1. New Project -> Spring Initializr,之後可以一路next。

這裡寫圖片描述

建立成功後可以看到如下的專案結構:
這裡寫圖片描述

2. 修改pom.xml檔案,新增必要依賴包:

<?xml version="1.0" encoding="UTF-8"?>
<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.deng.site</groupId> <artifactId>eurekaserver</artifactId> <version
>
0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>eurekaserver</name> <description>Eureka server</description> <parent> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-parent</artifactId
>
<version>Camden.SR7</version> </parent> <dependencies> <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> </project>

其中spring-cloud-starter-eureka-server即是eureka server必需的包,其他spring相關依賴包由parent繼承。

3. 修改application.properties

server.port=8761

eureka.instance.hostname=127.0.0.1
eureka.instance.prefer-ip-address=true

eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false

說明:
eureka.client.registerWithEureka: 為false意味著自身僅作為伺服器,不作為客戶端;
eureka.client.fetchRegistry: 為false意味著無需註冊自身。

4. 修改啟動類,並執行
修改EurekaServerApplication類,新增@EnableEurekaServer註解,然後執行。

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

最後訪問127.0.0.1:8761,看到如下頁面說明EurekaServer啟動成功:
這裡寫圖片描述

接下來會介紹Eureka Client配合Eureka Server的使用。