可重复使用的MicroProfile Health探针

严宇
2023-12-01

MicroProfile Health API是一个非常基本的API,它基于一个或多个Health Probe报告您的服务状态。 这在某些服务器或群集控制器需要决定是否以及何时重新启动实例的情况下非常有用。

在应用程序中使用MicroProfile Health API就像实现一个(或多个) org.eclipse.microprofile.health.HealthCheck并使用@Health注释类一样@Health

HealthCheck接口具有您应该实现的一种方法,即HealthCheckResponse call()

因此,您可以确定在调用此方法时,实例是否正常。

您的回复( HealthCheckResponse )包含:

  • 从其他探针识别此探针的名称
  • UPDOWN标志,以指示状态。
  • 键值对中要包含的任何其他元数据。

一个基本的例子。

假设我们有一个使用数据库的应用程序,并且如果与数据库的连接断开(或非常慢),则应报告此应用程序不正常:

@Health
    @ApplicationScoped
    public class MembershipHealthCheck implements HealthCheck {
    
        @Inject 
        private DataSource datasource;

        @Override
        public HealthCheckResponse call() {

            HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("membership");
            try {
                Connection connection = datasource.getConnection();
                boolean isValid = connection.isValid(timeout);

                DatabaseMetaData metaData = connection.getMetaData();

                responseBuilder = responseBuilder
                        .withData("databaseProductName", metaData.getDatabaseProductName())
                        .withData("databaseProductVersion", metaData.getDatabaseProductVersion())
                        .withData("driverName", metaData.getDriverName())
                        .withData("driverVersion", metaData.getDriverVersion())
                        .withData("isValid", isValid);

                return responseBuilder.state(isValid).build();


            } catch(SQLException  e) {
                log.log(Level.SEVERE, null, e);
                responseBuilder = responseBuilder
                        .withData("exceptionMessage", e.getMessage());
                return responseBuilder.down().build();
            }
        }
    }

(见完整的例子在这里

在上面的示例中,运行状况探测器名称为“ membership”,如果可以在一定时间内建立与数据库的连接,则报告UP 。 它还包括数据库的一些元数据字段。

/健康。

如果浏览到服务器上的/health ,您将看到来自所有探测的汇总响应以及服务器的总状态(“启动”或“关闭”)。

{
       "outcome":"UP",
       "checks":[
          {
             "name":"membership",
             "state":"UP",
             "data":{
                "databaseProductVersion":"5.5.5-10.1.35-MariaDB",
                "databaseProductName":"MySQL",
                "driverVersion":"mysql-connector-java-8.0.11 (Revision: 6d4eaa273bc181b4cf1c8ad0821a2227f116fedf)",
                "isValid":"true",
                "driverName":"MySQL Connector/J"
             }
          }
       ]
    }

如果数据库出现故障:

{
       "outcome":"DOWN",
       "checks":[
          {
             "name":"membership",
             "state":"DOWN",
             "data":{
                "exceptionMessage":"No operations allowed after connection closed."
             }
          }
       ]
    }

使用MicroProfile配置创建可重复使用的探针。

您的任何应用程序都可以重复使用某些运行状况探针,并且可以使用Microprofile Config API外部化设置。 例如,如果我们希望运行状况探针检查系统负载,则可以外部化系统负载应该在哪个阶段开始报告下来。

@Health
    @ApplicationScoped
    public class SystemLoadHealthCheck implements HealthCheck {

        @Inject @ConfigProperty(name = "health.systemload.max", defaultValue = "0.7")
        private double max;

        @Override
        public HealthCheckResponse call() {
            OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();

            String arch = operatingSystemMXBean.getArch();
            String name = operatingSystemMXBean.getName();
            String version = operatingSystemMXBean.getVersion();
            int availableProcessors = operatingSystemMXBean.getAvailableProcessors();

            double systemLoadAverage = operatingSystemMXBean.getSystemLoadAverage();
            double systemLoadAveragePerProcessors = systemLoadAverage / availableProcessors;

            HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("system-load")
                    .withData("name", name)
                    .withData("arch", arch)
                    .withData("version", version)
                    .withData("processors", availableProcessors)
                    .withData("loadAverage", String.valueOf(systemLoadAverage))
                    .withData("loadAverage per processor", String.valueOf(systemLoadAveragePerProcessors))
                    .withData("loadAverage max", String.valueOf(max));

            if(systemLoadAverage>0){
                boolean status = systemLoadAveragePerProcessors < max;
                return responseBuilder.state(status).build();
            }else{
                // Load average not available
                return responseBuilder.up().build();
            }

        }
    }

(见完整的例子在这里

在上面,我们现在可以通过更改health.systemload.max配置值将默认的0.7系统负载覆盖为我们自己的值。

其他示例可能包括:

  • 堆内存
  • 非堆内存
  • 线程数

在项目中使用它

您可以在项目中使用以上所有内容,因为它们可以在maven Central和github中使用

在您的pom.xml

<dependency>
        <groupId>com.github.phillip-kruger.microprofile-extensions</groupId>
        <artifactId>health-ext</artifactId>
        <version>1.0.9</version>
    </dependency>

/health的汇总结果可以如下所示:

{
       "outcome":"UP",
       "checks":[
          {
             "name":"system-load",
             "state":"UP",
             "data":{
                "name":"Linux",
                "arch":"amd64",
                "processors":"8",
                "loadAverage":"2.03",
                "version":"4.18.1-arch1-1-ARCH",
                "loadAverage max":"0.7",
                "loadAverage per processor":"0.25375"
             }
          },
          {
             "name":"membership",
             "state":"UP",
             "data":{
                "databaseProductVersion":"5.5.5-10.1.35-MariaDB",
                "databaseProductName":"MySQL",
                "driverVersion":"mysql-connector-java-8.0.11 (Revision: 6d4eaa273bc181b4cf1c8ad0821a2227f116fedf)",
                "isValid":"true",
                "driverName":"MySQL Connector/J"
             }
          },
          {
             "name":"non-heap-memory",
             "state":"UP",
             "data":{
                "max %":"0.9",
                "max":"-1",
                "used":"132792064"
             }
          },
          {
             "name":"threads",
             "state":"UP",
             "data":{
                "max thread count":"-1",
                "daemon thread count":"86",
                "monitor deadlocked thread count":"0",
                "thread count":"134",
                "deadlocked thread count":"0",
                "started thread count":"138",
                "peak thread count":"136"
             }
          },
          {
             "name":"heap-memory",
             "state":"UP",
             "data":{
                "max %":"0.9",
                "max":"14995161088",
                "used":"207556800"
             }
          }
       ]
    }

翻译自: https://www.javacodegeeks.com/2018/08/reusable-microprofile-health-probes.html

 类似资料: