Eureka目录导航
一、Eureka Client续约有什么问题吗?
Eureka Client默认会间隔30秒上报一次健康状态给Eureka Server,Server会认为你续约了那么你服务就是可用的,这其实不对的。
假设client要依赖DB提供服务,此时DB挂了,那么已经不能提供服务了,但是Server还能正常收到client的续约心跳,此时Server认为client还是正常提供服务的,那么其他服务使用就会出问题。
正常应该是通过服务的/health接口来判断服务是否可以提供正常服务。
二、利用spring-boot-starter-actuator实现/health
引入spring-boot-starter-actuator包,pom.xml增加如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>application.properties添加如下
# Actuator Web 访问端口
management.server.port=8084
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always重新启动eureka client客户端
访问 http://localhost:8083/actuator/

三、控制/health达到真实服务可用的控制
添加HealthController.java
package com.example.euprovider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HealthController {
@Autowired
HealthStatusService service;
@GetMapping("/health")
public String health(@RequestParam("status") boolean status) {
service.setStatus(status);
return "success";
}
}
添加HealthStatusService.java
package com.example.euprovider;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Service;
@Service
public class HealthStatusService implements HealthIndicator {
boolean status = true;
public void setStatus(boolean status) {
this.status = status;
}
@Override
public Health health() {
if (status) {
return new Health.Builder().up().build();
}
return new Health.Builder().down().build();
}
}
applicaion.properties添加如下
eureka.client.healthcheck.enabled=true重启eureka client
访问http://localhost:8083/health?status=false
访问 http://localhost:8083/actuator/health
f
查看eureka server中的服务状态,可以看到变为down,那么就不会将此实例下发给调用方。

四、总结
通过开启eureka.client.healthcheck.enabled=true来监听客户端的/health接口达到控制服务可用性的目的。
服务可以在异常出现时通过控制HealthIndicator 来控制服务的可用性。
将/actuator/heath改为down之后需要等续约时上报给Eureka Server,除此没有其他办法立即上报。
版权声明:本文为yaochuancun2原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。