服务注册与发现(eureka)

  • 本文springboot版本:2.0.2.RELEASE,springcloud版本:Finchley.RC1

创建eureka server

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

启动方法加上@EnableEurekaServer注解

1
2
3
4
5
6
7
8
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}

项目配置文件:bootstrap.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server:
port: 8761

spring:
application:
name: eureka-server

eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl.defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
# 关闭eureka自我保护机制
server:
enable-self-preservation: false
eviction-interval-timer-in-ms: 3000

然后启动项目,就有一个eureka server了,访问UI:http://localhost:8761

定制UI:http://springcloud.cn/view/250

创建eureka client

maven依赖:

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

项目配置文件:bootstrap.yml

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

spring:
application:
name: eureka-client
profiles:
active: dev
cloud:
config:
profile: ${spring.profiles.active} #dev,test,staging,prod
discovery:
enabled: true # 默认false,设为true表示使用注册中心中的configserver配置而不自己配置configserver的uri
serviceId: config-server # 指定config server在服务发现中的serviceId,默认为:configserver
eureka:
client:
serviceUrl.defaultZone: http://127.0.0.1:8761/eureka
instance:
hostname: localhost

启动client就可以在eureka server UI里看到注册成功了。

问题

如果发现服务关掉后,注册中心还一直有这个服务。可以关掉eureka的自我保护机制。
详见上面eureka server 的bootstrap.yml配置。

关于eureka自我保护机制:https://github.com/Netflix/eureka/wiki/Understanding-Eureka-Peer-to-Peer-Communication

本文源码

扩展阅读

微服务架构中基于DNS的服务发现


服务注册与发现(eureka)
https://www.wekri.com/springcloud/springCloudEureka/
Author
Echo
Posted on
May 17, 2018
Licensed under