eureka的默认的健康检查方式是heartbeat(心跳)。但是默认的heartbeat方式只会在注册时进行向eureka server(服务注册中心)发送eureka client的健康信息。这样一来就导致了两个问题:
要解决上述问题,默认可以通过配置eureka.client.healthcheck.enabled=true来完成。单独的配置该选项可以解决第一个问题但要想同时解决第二个问题我们必须同时实现HealthCheckHandler接口。具体步骤如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>
package com.mfs.microweatherbasic.config;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class MyHealthCheckHandler implements HealthCheckHandler {
@Value("${custom.service.weather-api}")
private String WEATHER_API;
@Autowired
private RestTemplate restTemplate;
private long time = 1;
@Override
public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus currentStatus) {
System.out.println(time++);
ResponseEntity<String> entity = restTemplate.getForEntity(WEATHER_API + "?city=临沂", String.class);
if (time > 3) {
return InstanceInfo.InstanceStatus.DOWN;
}
if (entity.getStatusCodeValue() == 200) {
return InstanceInfo.InstanceStatus.UP;
} else {
return InstanceInfo.InstanceStatus.DOWN;
}
}
}