Eureka服務注冊發現
服務發現:雲端負載均衡,一個基於 REST 的服務,用於定位服務,以實現雲端的負載均衡和中間層服務器的故障轉移。
1. Service Discovery: Eureka Server
Spring Cloud Netflix - Service Discovery: Eureka Server
Eureka服務端,實現服務注冊中心。
1.1 Eureka 注冊中心(注冊表)實現
1. 添加依賴
<!-- 注冊中心 --> <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>
2.application.yml配置
server:
port: 8761
security:
basic:
enabled: true #開啟認證
user:
name: user
password: 123456
eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://user:password@localhost:8761/eureka
3.主程序入口
@SpringBootApplication
@EnableEurekaServer//開啟Eureka Server
public class MicroserviceDiscoveryEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceDiscoveryEurekaApplication.class, args);
}
}
4.測試,瀏覽器訪問:http://localhost:8761/

2. Service Discovery: Eureka Clients
Spring Cloud Netflix - Service Discovery: Eureka Clients
Eureka客戶端,提供服務,進行服務注冊。
1.引入依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <!-- 用於注冊中心訪問賬號認證 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
2.application.yml配置
server:
port: 8081 #8181
spring:
application:
name: microservice-provider-user
eureka:
client:
serviceUrl:
defaultZone: http://user:123456@localhost:8761/eureka #注冊 中心已經開啟認證
instance:
prefer-ip-address: true
instanceId: ${spring.application.name}:${spring.application.instance_id:${server.port}}
3.主程序入口
@SpringBootApplication
@EnableEurekaClient //啟動EnableEureka客戶端
@RestController
public class MicroserviceProviderUserApplication {
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name){
System.out.println(name+" welcome . My is microservice provider user");
return name+" welcome . My is microservice provider user";
}
public static void main(String[] args) {
SpringApplication.run(MicroserviceProviderUserApplication.class, args);
}
}
