美文网首页
Spring Boot Actuator

Spring Boot Actuator

作者: waiting刘 | 来源:发表于2016-11-21 19:41 被阅读0次

什么是Actuator?

Spring Boot 包含了一系列的附加特性,来帮助你监控和管理生产环境下运行时的应用程序。你可以通过HTTP endpoints、JMX或者SSH来监控和管理应用——健康状况、系统指标、参数信息、内存状况等等。

HTTP endpoints 仅仅在基于Spring MVC的应用中可用。

开启Actuator

很简单,只需要引入官方提供的starter:

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

Endpoints

Actuator endpoints 允许对应用进行监控和交互。Spring Boot提供了很多内置的endpoint,同时支持定制的endpoint。

endpoint被暴露的方式取决于采用的技术(HTTP、JMX、SSH等),大部分应用采用HTTP的方式, 暴露的方式即通过endpoint的ID映射成一个URL,例如 health endpoint映射到/health, 提供应用基础健康检查信息, 为了安全起见,一般不暴露在应用服务端口上,而是暴露在专门的管理端口上。

几个通用内置endpoint

  • /health: 健康检查信息(服务启动状态、连接池状态等)
  • /info: 应用基础信息(应用名、介绍、版本信息、开发人员、git地址等)
  • /metrics:Java应用各项指标的监控(OS、JVM、应用各个层级的指标)
  • /trace:请求trace信息

endpoint定制

endpoint可以通过application.properties配置文件中的配置项进行定制, 格式如下:

endpoints.[name].[property]

有三个通用的property:

  • id: id
  • enable: 开关
  • sensitive: 是否需要权限控制才可以看到

以health为例,/health暴露的监控信息是所有实现了HealthIndicator接口的Bean。

通过自定义HealthIndicator实现定制health endpoint

@Component
public class HealthCheck implements HealthIndicator {
    @Override
    public Health health() {
        int errorCode = check(); // perform some specific health check
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }
     
    public int check() {
        // Your logic to check health
        return 0;
    }
}

输出类似如下格式:

{
    "status" : "DOWN",
    "myHealthCheck" : {
        "status" : "DOWN",
        "Error Code" : 1,
        "Description" : "You custom MyHealthCheck endpoint is down"
     },
     "diskSpace" : {
         "status" : "UP",
         "free" : 209047318528,
         "threshold" : 10485760
     }
}

创建新的Endpoint

一般通过自定义Endpoint<T>接口的实现创建一个新的endpoint。

@Component
public class CustomEndpoint implements Endpoint<List<String>> {
     
    public String getId() {
        return "customEndpoint";
    }
 
    public boolean isEnabled() {
        return true;
    }
 
    public boolean isSensitive() {
        return true;
    }
 
    public List<String> invoke() {
        // Custom logic to build the output
        List<String> messages = new ArrayList<String>();
        messages.add("This is message 1");
        messages.add("This is message 2");
        return messages;
    }
}

id=customEndpoint, 对应的URL为/customEndpoint

输出信息格式如下:

[ "This is message 1", "This is message 2" ]

参考文档

http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html

相关文章

网友评论

      本文标题:Spring Boot Actuator

      本文链接:https://www.haomeiwen.com/subject/tvbupttx.html