1. 简介
- 注册中心,服务注册与发现
- 服务提供者
- 服务消费者
- eureka 的注册表
1.3 其他服务发现组件
- Zookeeper
- Consul
1.4 其他
Run Dashboard 面板

2. Eureka Server 注册中心
2.1 pom.xml
父pom
<properties>
<spring-cloud.version>2021.0.5</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 子pom -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2.2 application.yml
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false # false表示不向注册中心注册自己
fetch-registry: false # false表示自己就是注册中心,不需要去检索服务
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
spring:
application:
name: concrete-eureka # 设置服务名字
server:
port: 8761
补充:
若不设置服务端 register-with-eureka: false 和 fetch-registry: false
启动报错: Connection refused
在默认设置下,eureka 会去注册中心获取其他服务的地址,也会将自己作为客户端来尝试注册它自己
2.3 启动类
@SpringBootApplication
@EnableEurekaServer
public class ConcreteEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(ConcreteEurekaApplication.class, args);
}
}
访问:http://localhost:8761/
3. Eureka Client 服务提供者
- 先启动服务端,再启动客服端
3.1 配置
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
server:
port: 8700
spring:
application:
name: concrete-eureka-client
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/ # 指定Eureka Server地址
3.2 示例
@SpringBootApplication
@EnableEurekaClient
public class ConcreteEurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConcreteEurekaClientApplication.class, args);
}
}
@RestController
public class ClientController {
@Value("${server.port}")
private String port;
@RequestMapping("/show")
public String show(String message) {
return "port: " + port + "; message: " + message;
}
}
3.3 @EnableDiscoveryClient 与 @EnableEurekaClient
- @EnableDiscoveryClient 注解是基于spring-cloud-commons依赖,并且在classpath中实现;
- @EnableEurekaClient注解是基于spring-cloud-netflix依赖,只能为eureka作用;
- 如果注册中心是eureka,那么就推荐@EnableEurekaClient,如果是其他的注册中心,用@EnableDiscoveryClient
网友评论