Spring Boot

spring boot actuator监控 详细介绍二

2019-04-10  本文已影响104人  X兄

自定义端点

一. 首先自定义健康监测的端点Health:

自定义健康监测的端点有两种方式:

  1. 继承AbstractHealthIndicator类 2. 实现HealthIndicator接口。
    第一种方法:
@Component("myHealth")   //myHealth 是你健康监测的名称
public class MyHealth extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        File[] rootFiles = File.listRoots();
        if (rootFiles != null && rootFiles.length != 0) {
            long total = 0, free = 0;
            for (File file : rootFiles) {
                total += file.getTotalSpace(); // 总量
                free += file.getUsableSpace(); // 未用
            }
            long user = total - free; // 已用
            double userRate = total == 0 ? 0 : ((double) user / total);// 利用率
            builder.up()
                    .withDetail("diskspaceTotal", total)   //这里是你要显示的具体健康监测信息
                    .withDetail("diskspaceFree", free)
                    .withDetail("diskspaceUsage", userRate * 100)
                    .build();
        } else {
            builder.down().build();
        }
    }
}

第二种健康监测方法:

@Component("helath2")//显示的名字
public class Health2 implements HealthIndicator {
    @Override
    public Health health() {
        int errorCode = new Random().nextInt(5); // 定义一个错误代码 随机产生
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();  //down就是不健康的状态
        } else {
            return Health.up().withDetail("Ok Code", errorCode).build();  //ok就是健康的状态
        }
    }
}

看看运行的检测结果:


health健康检测结果

二. 自定义Metrics端点
方法是implements MeterBinder

@Component
public class DiskMetrics implements MeterBinder {
    private File rootFilePath;

    public DiskMetrics() {
        this.rootFilePath = new File(".");
    }

    @Override
    public void bindTo(@NotNull MeterRegistry registry) {
        // 磁盘已用容量
        Gauge.builder("磁盘已用容量", rootFilePath, File::getTotalSpace)
                .register(registry);
        // 磁盘剩余容量
        Gauge.builder("磁盘剩余容量", rootFilePath, File::getFreeSpace)
                .register(registry);
        // 磁盘使用率
        Gauge.builder("磁盘使用率", rootFilePath, c -> {
            long totalDiskSpace = rootFilePath.getTotalSpace();
            if (totalDiskSpace == 0) {
                return 0.0;
            }
            long usedDiskSpace = totalDiskSpace - rootFilePath.getFreeSpace();
            return (double) usedDiskSpace / totalDiskSpace * 100;
        })
                .register(registry);
    }
}

需要你注意的是 开头的@Component注解不要忘记了
自定义的Metrics端点的运行结果:

自定义Metrics端点

三. 自定义一个你要的端点
需要用到以下注解:
@Endpoint、 @ReadOperation、@WriteOperation、@DeleteOperation

/**
 * 自定义端点的一种方式
 *
 */
@Endpoint(id = "person")  //显示的端点名
@Component
public class PersonEndpoint {
    /**
     * 自定义端点
     * 通过@Endpoint、 @ReadOperation、@WriteOperation、@DeleteOperation
     * @Endpoint: 构建 rest api 的唯一路径
     * @ReadOperation: GET请求,响应状态为 200 如果没有返回值响应 404(资源未找到)
     * @WriteOperation: POST请求,响应状态为 200 如果没有返回值响应 204(无响应内容)
     * @DeleteOperation: DELETE请求,响应状态为 200 如果没有返回值响应 204(无响应内容)
     */

    private final Map<String, Person> people = new HashMap<>();

    PersonEndpoint() {
        this.people.put("mike", new Person("Michael Redlich"));
        this.people.put("rowena", new Person("Rowena Redlich"));
        this.people.put("barry", new Person("Barry Burd"));
    }

    @ReadOperation
    public List<Person> getAll() {
        return new ArrayList<>(this.people.values());
    }

    @ReadOperation
    public Person getPerson(@Selector String person) {
        return this.people.get(person);
    }

    @WriteOperation
    public void updatePerson(@Selector String name, String person) {
        this.people.put(name, new Person(person));
    }

    public static class Person {
        private String name;

        Person(String name) {
            this.name = name;
        }

        public String getName() {
            return this.name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

自定义的端点person运行结果:


自定义的端点person

还可以访问http://localhost:8088/person/名字 如:http://localhost:8088/person/mike
结果:

name

实现自定义端点
如果您添加带@Bean注释的@Endpoint注释@ReadOperation,通过JMX 注释的任何方法 @WriteOperation,或者@DeleteOperation通过JMX自动公开,以及在Web应用程序中也通过HTTP 添加注释。可以使用Jersey,Spring MVC或Spring WebFlux通过HTTP公开端点。

您还可以使用@JmxEndpoint或 编写特定于技术的端点@WebEndpoint。这些端点仅限于各自的技术。例如,@WebEndpoint仅通过HTTP而不是通过JMX公开。

您可以使用@EndpointWebExtension和 编写特定于技术的扩展@EndpointJmxExtension。通过这些注释,您可以提供特定于技术的操作来扩充现有端点。

最后,如果您需要访问特定于Web框架的功能,则可以实现Servlet或Spring @Controller和@RestController端点,但代价是它们不能通过JMX或使用不同的Web框架。

更多问题,请自行访问官方介绍actuator官方文档

上一篇 下一篇

猜你喜欢

热点阅读