概要
微服務框架中最爲核心和基礎的模塊就是服務治理,它主要用來實現各個微服務實例的自動化註冊與發現。在這個體系結構中有一個“中心點”——服務註冊中心,每個服務必須註冊到服務註冊中心。而各個服務之間進行通訊並不需要知道具體服務的主機名和端口。這種實現的一個缺點是所有客戶機必須實現某種邏輯來與這個中心點進行交互,這樣在實現服務請求之前將增加一次額外的網絡往返。
Spring Cloud 使用 Netflix Eureka
來實現服務註冊與發現,它既包含了服務端組件,也包含了客戶端組件。Eureka服務端也稱爲服務註冊中心,支持高可用配置。它依託強一致性提供良好的服務實例可用性。Eureka客戶端可以同時充當服務器,將其狀態複製到一個連接的對等點上。換句話說,客戶機檢索服務註冊中心所有連接的節點的列表,並通過負載平衡算法向所有其他服務發出請求。每個客戶機爲了聲明自己的存活狀態,他們必須向註冊中心發送一個心跳信號。在本例中爲了體現服務治理功能,實現了三個微服務:
一個服務註冊中心 (Eureka Server) 一個在註冊中心註冊的REST服務(Eureka Client)
一個Web應用程序,服務的消費者(Spring Cloud Netflix Feign Client)
1.註冊中心
使用Spring Cloud Netflix Eureka實現一個註冊中心非常簡單。在pom裏增加spring-cloud-starter-eureka-server依賴,在啓動類裏添加@EnableEurekaServer註解。
@EnableEurekaServer //開啓Eureka Server
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/>
</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-security</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Edgware.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
第二步:創建啓動類
package com.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @PACKAGE_NAME PACKAGE_NAME
* @PROJECT_NAME springcloudeurekaregister
* @創建人 huang
* @創建時間 2018/11/26
*/
@SpringBootApplication
@EnableEurekaServer //開啓Eureka Server
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class,args);
}
}
修改全局配置文件application.yaml:
server:
port: 8888 #服務註冊中心端口號
security:
basic:
enabled: true #開啓認證
user: #登錄eureka的用戶名和密碼
name: user
password: 123456
eureka:
instance:
hostname: localhost #服務註冊中心實例的主機名
client:
register-with-eureka: false #是否向服務註冊中心註冊自己
fetch-registry: false #是否檢索服務
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
瀏覽器輸入http://localhost:8888/可以看到Eureka的控制檯,在那裏能看到將來註冊後的服務實例和一些狀態和健康指標。