【Spring实战】23 Spring Actuator 常用的自定义

文章目录

    • 1. 自定义健康指示器
    • 2. 自定义端点
    • 3. 自定义端点路径
    • 4. 自定义 Actuator 端点的访问权限
    • 5. 启动服务
    • 6. 访问自定义的 custom 端点
    • 总结

Spring Actuator 是 Spring 框架的一个模块,为开发人员提供了一套强大的监控和管理功能。上一篇 【Spring实战】22 Spring Actuator 入门 文章中 介绍了它的定义、功能、集成、配置以及一些常见的应用场景。 本文将介绍Spring Boot Actuator 的几种常见的自定义配置以供我们使用。

1. 自定义健康指示器

想要实现自定义健康指示器,我们可以实现 org.springframework.boot.actuate.health.HealthIndicator 接口,并覆盖 health() 方法。这样你可以创建自定义的健康指示器,并将其添加到应用程序中。

例子:

package com.cheney.demo.health;

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

@Component
public class CustomHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        // 自定义健康检查逻辑
        return Health.up().build();
    }
}

2. 自定义端点

想要实现自定义端点,我们可以创建一个类,并且去实现 org.springframework.boot.actuate.endpoint.annotation.Endpoint 接口。使用 @Endpoint 注解标记这个类。

例子:

package com.cheney.demo.health;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

@Component
@Endpoint(id = "custom")
public class CustomEndpoint {

    @ReadOperation
    public String customEndpoint() {
        // 自定义端点处理
        return "自定义端点的处理";
    }
}

3. 自定义端点路径

想要自定义端点路径,我们可以在配置文件中,使用 management.endpoints.web.base-path 属性来自定义端点的基础路径。

例子:

management.endpoints.web.base-path=/cheney-actuator

然后,你的自定义端点将在 /cheney-actuator 下可用。

4. 自定义 Actuator 端点的访问权限

想要自定义 Actuator 端点的访问权限,我们可以使用 management.endpoints.web.exposure.includemanagement.endpoints.web.exposure.exclude 属性来控制哪些端点对外暴露。这可以用于定制端点的访问权限。

management.endpoints.web.exposure.include=health,info,metrics,custom

在上述示例中,custom 是你自定义的端点 ID。

5. 启动服务

【Spring实战】23 Spring Actuator 常用的自定义_第1张图片

6. 访问自定义的 custom 端点

http://localhost:8080/cheney-actuator/custom

在这里插入图片描述

总结

这些是一些常见的自定义 Spring Boot Actuator 的方式。你可以根据实际需求选择合适的方式,以满足你的应用程序监控和管理的需求。

你可能感兴趣的:(Spring实战,spring,java,后端,springboot)