Spring Cloud 服务注册与发现(Eureka)

Eureka是一种基于REST(Representational State Transfer)的服务,主要用于AWS云,用于定位服务,以实现中间层服务器的负载平衡和故障转移。是Netflix开源的一款提供服务注册和发现的产品,它提供了完整的Service Registry和Service Discovery实现。也是Spring Cloud体系中最重要最核心的组件之一。

GitHub:Eureka

Eureka Server 服务注册与发现服务端

pom.xml中添加依赖

1
2
3
4
5
6
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>

启动类中添加@EnableEurekaServer注解

1
2
3
4
5
6
7
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}

yml配置文件 YAML语言

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server:
port: 8765

spring:
application:
name: eureka-server

#单机版
eureka:
instance:
hostname: localhost #eureka服务端名称
prefer-ip-address: true #以IP地址注册到服务中心,相互注册使用IP地址
client:
register-with-eureka: false #false表示不向注册中心注册自己
fetch-registry: false #false表示自己就是注册中心,职责就是维护服务实例,不需要检索服务
service-url: #设置eureka Server交互的地址查询服务和注册服务都需要依赖此地址
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
server:
peer-node-read-timeout-ms: 600 #读取对等节点服务器复制的超时的时间
eviction-interval-timer-in-ms: 4000 #服务刷新间隔时常(毫秒)
enable-self-preservation: false #禁用自我保护机制
renewal-percent-threshold: 0.9 #触发自我保护的心跳数比例阈值

启动工程

在浏览器访问 http://localhost:8765/ ,此时一个服务也没有

Eureka Client 服务提供者客户端

pom.xml中添加依赖

1
2
3
4
5
6
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>

启动类中添加@EnableEurekaServer注解

1
2
3
4
5
6
7
@EnableEurekaClient
@SpringBootApplication
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}

yml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
server:
port: 9001

spring:
application:
name: eureka-client

eureka:
instance:
prefer-ip-address: true #访问路径可以显示ip地址
instance-id: eureka-client #微服务别名
client: #客户端注册进eureka服务列表
service-url:
defaultZone: http://localhost:8765/eureka/

启动工程

刷新浏览器,发现客户端已成功注册

相关文档

Eureka Server
Eureka Client

0%