Eureka
大约 2 分钟
What's Eureka?
相关信息
注册中心,AP设计,保证了可用性,牺牲了一致性。
去中心化(无主从节点),各个节点都是平等的,一个节点挂了,自动切换其他节点可以使用,服务节点间的数据可能不一致。
只要有一台 Eureka 还在,就能保证注册服务可用,但是查到的信息可能不是最新的。
保护机制
Eureka 自我保护机制,如果 15 分钟内超过 85% 的节点都没有正常的心跳,那么 Eureka 就认为客户端与注册中心出现了网络故障,
此时:
- Eureka 不再从注册列表中移除因长时间没收到心跳而应该过期的服务。
- Eureka 仍然能够接受新服务的注册和查询请求,但是不会被同步到其他节点上(保证当前节点依然可用)。
- 当网络稳定时,当前实例新的注册信息会被同步到其他节点中。
因此,Eureka 可以很好的应对因网络故障导致部分节点失去联系的情况,而不会像 Zookeeper 那样整个注册服务瘫痪。
使用Eureka
- 添加 Eureka 相关依赖。
- 在启动类上添加注解
@EnableEurekaServer
声明该项目为 Eureka 注册中心服务器。 - 配置
application.yml
. - 访问注册中心页面。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
# 服务配置
server:
port: 8050 # 注册中心端口号
# eureka相关配置
eureka:
instance:
hostname: 127.0.0.1 # 注册中心服务器名称
client:
register-with-eureka: false # 该注册中心是否接收http请求(没有控制层)
fetch-registry: false # 是否拉取服务信息
service-url:
defaultZone: http://127.0.0.1:8050/eureka/ # 客户端要连接注册中心使用该地址
客户端搭建
- 添加 Eureka 服务注册和发现依赖。
- 在启动类上添加注解
@EnableEurekaClient
声明该项目是被 Eureka 接管的项目。 - 在
application.yml
中添加配置文件,指定注册中心的路径。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
# 配置服务
server:
port: 8081 # 服务端口号
# 连接注册中心的配置
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8050/eureka/
# 该服务在注册中心的名称
spring:
application:
name: goods-server
# freemarker
freemarker:
suffix: .html
cache: false
# oracle
datasource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
username: ly
password: tiger
# redis
redis:
database: 0
host: 127.0.0.1
port: 6379
# mybatis
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.ly.pojo