spring cloud 注冊與發現
在這裡使用Eureka作為注冊中心。
一、eureka-server
建立新的module:eureka-server
1.1 引入eureka-server依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
1.2 配置檔案
server.port=8761
#eureka server
eureka.instance.hostname=localhost
#注冊到eureka服務中心
eureka.client.register-with-eureka=false
#檢索服務
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
1.3 啟動類
啟動類添加注解@EnableEurekaServer
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
二、eureka-client
建立新的module:eureka-client
2.1 引入eureka-client坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
2.2 配置檔案
#注冊進eureka,預設true
server.port=8001
eureka.client.register-with-eureka=true
#預設true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
spring.application.name=eureka-client
2.3 啟動類
啟動類添加注解@EnableEurekaClient
@EnableEurekaClient
@SpringBootApplication
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}
三、檢視注冊中心
通路eureka注冊中心,可以檢視已經注冊到eureka的服務有哪些。
3.1 運作
依次啟動eureka-server、eureka-client

3.2通路
通路http://localhost:8761
在這裡可以看到已經注冊進來的執行個體都有哪些。
010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101