1. 程式人生 > >SpringCloud實戰二:Spring Cloud Eureka 服務發現與註冊中心

SpringCloud實戰二:Spring Cloud Eureka 服務發現與註冊中心

  Spring Cloud Eureka 它是通過封裝 Netflix 開源的Eureka,一款基於 Rest 的服務發現與註冊元件,包括 Eureka Server 和 Eureka Client,最新版本為2018年8月釋出的1.9.4版本,最新的2.x版本已經不再開源,但是1.9版本已經夠用了,不要太過擔心
  為什麼需要服務註冊中心?先看幾張服務之間呼叫圖

  • 專案A寫死專案B的IP和埠進行服務間呼叫
    在這裡插入圖片描述
  • 如果專案B再以同樣的方式訪問專案C,當專案B的IP和埠放生變化時,整個呼叫就會失敗
    在這裡插入圖片描述
  • 當有了Eureka註冊中心後,會是什麼樣子,請看簡圖
    在這裡插入圖片描述
    上圖就是為什麼會有註冊中心的原因
    除了Eureka外,還有Consul註冊中心,Spring Cloud 也整合 Consul
    有了上面的理論基礎後,我們進行程式碼實踐
通過IDEA建立Maven工程,刪除src目錄,再新增2個Module,分別是eureka-server 、eureka-client

在這裡插入圖片描述

  • eureka-server 的 pom.xml內容如下(為了篇幅,只顯示主要部分,想看全部程式碼的可以下載):
	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Finchley.SR2</spring-cloud.version>
	</properties>

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

eureka-server的啟動主類,新增一個 @EnableEurekaServer註解即可

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

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

eureka-server的application.properties配置檔案如下:

server.port=10025
eureka.instance.hostname=localhost
eureka.instance.prefer-ip-address=true
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

  • eureka-client 的 pom.xml內容如下,其他和eureka-server相同:
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

eureka-client的啟動主類,新增一個 @EnableDiscoveryClient註解即可

@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {

	public static void main(String[] args) {
		SpringApplication.run(EurekaClientApplication.class, args);
	}
}

eureka-client的application.properties配置檔案如下:

server.port=9500
#服務的例項名,服務間的呼叫通過此名字呼叫
spring.application.name=eureka-client
#填寫eureka註冊中心地址,把自己註冊到註冊中心去
eureka.client.serviceUrl.defaultZone=http://localhost:10025/eureka/

好了,分別啟動 eureka-server、eureka-client,然後訪問 http://localhost:10025/,可以看到eureka-client服務例項已經註冊到註冊中心了,後面還有該例項的 IP與埠
在這裡插入圖片描述

一個簡單的註冊中心就搞定了,當然此時它還不能用於生產環境,後面演示註冊中心高可用與安全
原始碼已上傳到碼雲,https://gitee.com/zhuyu1991/spring-cloud/