SpringCloud 3:Eureka 健康检测

项目搭建参考https://blog.csdn.net/qq_40977118/article/details/104738485

1. 健康检测

  • Eureka 默认的健康检测只是你校验服务连接是否是 UP 还是 DOWN 的,然后客户端只会调用状态为 UP 状态的服务,但是有的情况下,虽然服务连接是好的,但是有可能这个服务的某些接口不是正常的,可能由于需要连接 Redis,mongodb 或者 DB 有问题导致接口调用失败, 所以理论上服务虽然能够正常调用,但是它不是一个健康的服务。所以我们就有必要对这种情况做自定义健康检测。

2. application.properties 配置

在这里插入图片描述

eureka.client.healthcheck.enabled=true

3. 引入jar包

在这里插入图片描述

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

4. 添加一个接口检测数据库连接

  • 这里通过调用接口,模拟修改数据库的连接状态
    在这里插入图片描述
package com.spring.fisher.Controller;

import com.spring.fisher.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/queryUser")
    public String queryUser() {
        return userService.queryContents();
    }
    public static boolean dbFlag = true;
    /**
     * 检测db连接是否ok
     */
    @RequestMapping("/db/{can}")
    public void setDb(@PathVariable boolean can) {
        dbFlag = can;
    }

}

5. 创建一个健康检测实现类

  • 正常情况下应该在 health 方法里面去连接数据库,如果连接异常了则返回 DOWN,如果没异常则返回 UP,这个 health 方法是线程去调用的,隔一段时间调用一次,这里为了方便,使用上面的接口来修改数据库的连接状态

在这里插入图片描述

package com.spring.fisher.health;

import com.spring.fisher.Controller.UserController;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MicroWebHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        if (UserController.dbFlag) {
            return new Health.Builder(Status.UP).build();
        }else {
            return new Health.Builder(Status.DOWN).build();
        }
    }
}

6. 启动项目,查看服务列表

在这里插入图片描述
在这里插入图片描述

7. 查看健康状态

  • http://localhost:8083/actuator/health

在这里插入图片描述

8. 修改数据库连接状态

  • http://localhost:8083/db/false
    在这里插入图片描述

9. 再次查看健康状态

  • {“status”:“DOWN”}

在这里插入图片描述

10. 再次查看服务列表

  • DOWN (1) - DESKTOP-LT2HQFS:micro-web:8083

在这里插入图片描述

代码下载地址

https://gitee.com/fisher3652/springcloud-eureka.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值