Spring-boot 添加自定义健康检测 /actuator/health

一、如何添加自己的一个健康检测项到检测体系里


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

/**
 *  添加一个自定义的健康监测
 * Author: zhangjianshou <br>
 * Description:
 * @Date: 2022/12/28 17:25
 */
@Component
public class LocalDiyHealth implements HealthIndicator {

    private static final Logger log = LoggerFactory.getLogger(LocalDiyHealth.class);

    /**
     * Description: 自定义健康监测接口,http://127.0.0.1/actuator/health,请求时候,会触发本方法
     * @author zhangjianshou
     * @param includeDetails
     * @return:
     * @Exception:  </br>
     * @Date: 2022/12/28 17:38
     */
    @Override
    public Health getHealth(boolean includeDetails) {
        log.debug("正在检查health...");
        Health.Builder up = Health.up().withDetail("我是健康的", "up up");
        try {
            /*if (up != null) {
                throw new Exception("test  down");
            }*/
            return up.build();
        } catch (Exception e) {
            log.error("检查异常", e);
            return Health.down().withException(e).withDetail("我是不健康的", "down down").build();
        }
    }

    @Override
    public Health health() {
        log.debug("正在检查health...");
        Health.Builder up = Health.up().withDetail("localDiyHealth", "up");
        try {
            return up.build();
        } catch (Exception e) {
            log.error("检查异常");
            return up.withException(e).build();
        }
    }
}

二、如果开发了一个组件,想让用户引入组件后,让spring自动检测该组件,下面以nacos为例

  1. 组件代码里添加定义选项
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;

public class DiyNacosConfigHealthIndicator extends AbstractHealthIndicator {

    private final ConfigService configService;

    public DiyNacosConfigHealthIndicator(ConfigService configService) {
        this.configService = configService;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        // Just return "UP" or "DOWN"
        String status = configService.getServerStatus();
        // Set the status to Builder
        builder.status(status);
        switch (status) {
        case "UP":
            builder.up();
            break;
        case "DOWN":
            builder.down();
            break;
        default:
            builder.unknown();
            break;
        }
    }

}
  1. 注册健康检测选项
 
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.dhgate.zjs.health.indicator.DiyNacosConfigHealthIndicator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;

/**
 * @author xiaojing
 */
@ConditionalOnWebApplication
@ConditionalOnClass(Endpoint.class)
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigEndpointAutoConfiguration {

    @Autowired
    private NacosConfigManager nacosConfigManager;

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnEnabledHealthIndicator("nacos-config")
    public DiyNacosConfigHealthIndicator nacosConfigHealthIndicator() {
        return new DiyNacosConfigHealthIndicator(nacosConfigManager.getConfigService());
    }

}
  1. 启动工程请求地址:http://127.0.0.1:8081/actuator/health

就会出现如下

{"status":"UP","components":{"diskSpace":{"status":"UP","details":{"total":"500106792960","free":"215939887104","threshold":"10485760","exists":true}},"nacos":{"status":"UP"}}}

### 集成 `spring-boot-starter-actuator` 和 Gateway 为了在 Spring Boot 项目中成功集成 `spring-boot-starter-actuator` 和 Gateway,需遵循特定配置方法。 #### 添加依赖项 首先,在项目的 `pom.xml` 文件中添加必要的 Maven 依赖项: ```xml <dependencies> <!-- Actuator --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- WebFlux for Gateway --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- 移除 spring-boot-starter-web 并确保不会引入冲突的Web组件 [^2]--> </dependencies> ``` 注意移除了 `spring-boot-starter-web` 以防止与网关模块发生冲突。这一步骤对于避免潜在启动失败至关重要。 #### 启用端点暴露 接着修改 `application.yml` 或者 `application.properties` 来启用并自定义 actuator 的行为: ```yaml management: endpoints: web: exposure: include: "*" # 暴露所有默认端点 endpoint: health: show-details: always # 始终显示健康详情 ``` 此设置允许通过 HTTP 访问所有的管理端点,并且当查询 `/actuator/health` 路径时总是返回详细的健康状态信息。 #### 自定义路由规则 (可选) 如果希望进一步定制化 API 网关的行为,则可以在应用程序属性文件里指定额外的路由规则或其他配置选项。例如: ```yaml spring: cloud: gateway: routes: - id: example_route uri: http://example.org/ predicates: - Path=/api/** ``` 上述 YAML 片段创建了一个名为 "example_route" 的新路由,它会匹配任何以 "/api/" 开头的请求并将它们转发给目标 URI。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值