Eureka 是一個服務註冊與發現的組件,用於微服務管理服務的信息,便於服務之間進行通訊
一.搭建Eureka
1.搭建Eureka Server,創建一個SpringBoot項目,引入Eureka Server依賴
2.編寫Eureka Server 的 application.yml配置文件
#服務端口號
server:
port: 8000
spring:
application:
name: app-eureka
#eureka 基本信息配置
eureka:
instance:
#註冊中心ip地址
hostname: 127.0.0.1
client:
serviceUrl:
#註冊到的Eureka Server地址
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
#因爲自己是爲註冊中心,不需要自己註冊自己
register-with-eureka: false
#因爲自己是爲註冊中心,不需要檢索服務
fetch-registry: false
3.在啓動類中加入Eureka Server啓動註解
package com.xx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerDemoApplication.class, args);
}
}
4.搭建Eureka Client,創建一個SpringBoot項目,引入Web和Eureka Server依賴
5.編寫Eureka Client 的 application.yml配置文件
#服務啓動端口號
server:
port: 8100
#服務名稱(服務註冊到eureka名稱)
spring:
application:
name: app-member
#將Member服務的ip和端口信息註冊到Eureka Server中
eureka:
client:
service-url:
#Eureka Server地址
defaultZone: http://localhost:8000/eureka
#將服務註冊到Eureka中
register-with-eureka: true
#從Eureka獲取註冊信息
fetch-registry: true
6.在啓動類中加入Eureka Client啓動註解
package com.xx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class MemberApplication {
public static void main(String[] args) {
SpringApplication.run(MemberApplication.class, args);
}
}
二.搭建Eureka集羣
再創建一個Eureka Server,並使它們之間相互註冊
#服務端口號
server:
port: 8000
spring:
application:
name: app-eureka
#eureka 基本信息配置
eureka:
instance:
#註冊中心ip地址
hostname: 127.0.0.1
client:
serviceUrl:
#將自己註冊進端口爲9000的Eureka Server
defaultZone: http://${eureka.instance.hostname}:9000/eureka/
#搭建集羣需要將自己也註冊進去
register-with-eureka: true
fetch-registry: true
#服務端口號
server:
port: 9000
spring:
application:
name: app-eureka
#eureka 基本信息配置
eureka:
instance:
#註冊中心ip地址
hostname: 127.0.0.1
client:
serviceUrl:
#將自己註冊進端口爲8000的Eureka Server
defaultZone: http://${eureka.instance.hostname}:8000/eureka/
#搭建集羣需要將自己也註冊進去
register-with-eureka: true
fetch-registry: true