Spring Cloud Eureka Server
1. 通过spring.io创建工程,需要选择Eureka Server依赖
2. 确认有以下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
3. 主类中使用注解开启eurekaServer
@SpringBootApplication
@EnableEurekaServer
public class EurekaserverApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaserverApplication.class, args);
}
}
4. application.properties配置
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
作为唯一一台eurekaServer,设置不需要向注册中心注册,不需要检索注册服务
更多关于eureka的配置可查看EurekaServerConfigBean/EurekaClientConfigBean/EurekaInstanceConfigBean
5. 查看注册中心页面,8080为默认端口
Spring Cloud Eureka Client
1. 通过spring.io创建工程时选择Eureka Discovery依赖或者直接在pom.xml中增加以下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2. 主类中使用注解开启eurekaClient
@SpringBootApplication
@EnableEurekaClient
public class LblserviceApplication {
public static void main(String[] args) {
SpringApplication.run(LblserviceApplication.class, args);
}
}
3.配置文件
#向注册中心注册
eureka.client.register-with-eureka=true
#检索注册服务
eureka.client.fetch-registry=true
#eurekaServer地址
#此处应该是eurekaServer访问页面的地址再加上/eureka/后缀
#这里的defaultZone不能写成default-zone,否则会无法注入
eureka.client.service-url.defaultZone=http://localhost:8080/eureka/
#服务名字
spring.application.name=lblService
#instance优先使用IP而不是域名
eureka.instance.preferIpAddress=true
#配置IP地址,用于后面生成instanceId
spring.cloud.client.ipAddress=1.1.1.2
#配置instanceId
eureka.instance.instance-id=${spring.cloud.client.ipAddress}:${server.port}
更多关于eureka的配置可查看EurekaServerConfigBean/EurekaClientConfigBean/EurekaInstanceConfigBean
4. 启动后可以在eurekaServer的页面中看到lblService这个服务
5. 在lblService中可以通过名称获取其余注册服务
client.getInstances("configServer").stream().forEach(instance ->{
System.out.println(instance.getHost() + ":" + instance.getPort());
});
client.getInstances("lblService").stream().forEach(instance ->{
System.out.println(instance.getHost() + ":" + instance.getPort());
});
疑惑:
将eurekaClient停掉后注册中心依然显示该服务,搜索资料得
自我保护机制的工作机制是如果在15分钟内超过85%的客户端节点都没有正常的心跳,那么Eureka就认为客户端与注册中心出现了网络故障,Eureka Server自动进入自我保护机制,此时会出现以下几种情况:
1、Eureka Server不再从注册列表中移除因为长时间没收到心跳而应该过期的服务。
2、Eureka Server仍然能够接受新服务的注册和查询请求,但是不会被同步到其它节点上,保证当前节点依然可用。
3、当网络稳定时,当前Eureka Server新的注册信息会被同步到其它节点中。
因此Eureka Server可以很好的应对因网络故障导致部分节点失联的情况,而不会像ZK那样如果有一半不可用的情况会导致整个集群不可用而变成瘫痪。
引自: https://blog.csdn.net/akaks0/article/details/79512680
#通过此配置可关闭自我保护
eureka.server.enableSelfPreservation=false
#通过此可以调整eureka的检查服务区间
eureka.server.evictionIntervalTimerInMs=10000
问题是如此调整后,服务依然没有被移除