1. 程式人生 > >Spring Cloud 學習紀要一:Eureka

Spring Cloud 學習紀要一:Eureka

Spring Cloud Eureka:服務治理

  Spring Cloud Eureka是Spring Cloud Netflix服務套件中的一部分,它基於Netflix Eureka做了二次封裝,主要負責完成微服務架構中的服務治理,接下來將展示入門Demo。

開發環境 版本
IDEA 2018.2.6
JDK 1.8
Spring Boot 2.1.0
Spring Cloud Greenwich.M1

Eureka服務端

新建專案

  在IDEA中通過Spring Initializr建立專案,選擇Spring Boot 2.1.0版本、選擇Maven依賴Eureka Server(Cloud Discovery中)。

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

加入註解

  在入口類新增@EnableEurekaServer註解。

@SpringBootApplication
@EnableEurekaServer // 開啟Eureka註冊服務
public class EurekaApplication {
    public static
void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }

新增配置

  在檔案application.yml新增配置。

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
    register-with-eureka: false #禁止自身註冊
#  server:
#    enable-self-preservation: false
  instance:
    prefer-ip-address: true  #預設顯示IP
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    #    hostname: ServerName

spring:
  application:
    name: eureka

執行專案

  在VM options設定-DServer.port=8761,執行專案,瀏覽器開啟http://localhost:8761即可看到Eureka頁面。
Eureka Server

Eureka客戶端

新建專案

  在IDEA中通過Spring Initializr建立專案,選擇Spring Boot 2.1.0版本、選擇Maven依賴Web和Eureka Discovery(Cloud Discovery中)。

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

加入註解

  在入口類新增@EnableEurekaClient註解。

@SpringBootApplication
@EnableEurekaClient //開啟Eureka發現
public class FeignProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignProviderApplication.class, args);
    }
}

新增配置

  在檔案application.yml新增配置。

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    #    hostname: ProviderName
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
spring:
  application:
    name: provider

執行專案

  在VM options設定-DServer.port=8081,執行專案,在Eureka頁面可以看到如下圖線框處,證明本專案啟動時已自動註冊成功。
EurekaClient