eureka的HealthChecks(健康检查)

eureka的默认的健康检查方式是heartbeat(心跳)。但是默认的heartbeat方式只会在注册时进行向eureka server(服务注册中心)发送eureka client的健康信息。这样一来就导致了两个问题:

  1. eureka客户端的健康状态发生变化时在服务注册中心对应实例的状态不能得到更新。比如我们的一个eureka客户端的运行,这时在注册中心却不能意识到该服务已经停止。
  2. eureka客户端运行正常,但是它所依赖的其他资源却挂掉了。比如Mysql数据库或者依赖的其他接口挂掉了。这时使用默认的heartbeat的方式也不能够检查出来。面对这种情况我们必须提供一种更加适应我们应用的健康检查方式。

要解决上述问题,默认可以通过配置eureka.client.healthcheck.enabled=true来完成。单独的配置该选项可以解决第一个问题但要想同时解决第二个问题我们必须同时实现HealthCheckHandler接口。具体步骤如下:

  1. 添加spring-boot-actuator依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-actuator</artifactId>
</dependency>
  1. 在application.properties配置文件中添加eureka.client.healthcheck.enabled=true
  2. 实现HealthCheckHandler接口
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;
        }
    }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

M FS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值