Springboot中使用Actuator监控项目

一、Actuator介绍

在企业应用中除了要了解Spring Boot业务的单元测试、集成测试等功能使用外,在上线之后还需要对线上应用的各项指标(比如,CPU利用率、内存利用率、数据库连接是否正常、用户请求数据等)进行监控和运维。
在传统项目中,这些监控和运维往往需要借助其他第三方的工具实现,而在Spring Boot中提供了spring-boot-actuator模块,对于小型项目够用了,可以通过http、jmx、ssh、telnet等形式来监控和管理生产环境。同时,Spring Boot还提供了灵活的自定义接口用来扩展监控的功能。

二、Actuator监控应用

1、引入Actuator

Spring Boot Actuator提供了应用的审计 (Auditing)、健康(Health)状态信息、数据采集(Metrics gathering)统计等监控运维的功能。

同时,还提供了可扩展的端点(Endpoint)功能,方便使用者进行自定义监控指标。默认情况下,这些信息以jSON的数据格式呈现,用户也可以使用Spring BootAdmin项目进行界面管理
Actuator 是 Spring Boot 提供的对应用系统的自省和监控的集成功能,可以查看应用配置的详细信息,例如自动化配置信息、创建的 Springbeans 以及一些环境属性等。
为了保证 atuator 暴露的监控接口的安全性,需要添加安全控制的依赖 spring-boot-start-securty依赖,访问应用监控端点时,都需要输入验证信息。Security 依赖,可以选择不加,不进行安全管理,但不建议这么做。

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

原生端点是在应用程序里提供众多 Web 接口,通过它们了解应用程序运行时的内部状况。原生端点又可以分成三类:

  1. 应用配置类:可以查看应用在运行期的静态信息:例如自动配置信息、加载的 springbean 信息、yml文件配置信息、环境信息、请求映射信息
  2. 度量指标类:主要是运行期的动态信息,例如堆栈、请求连、一些健康指标、metrics 信息等
  3. 操作控制类:主要是指shutdown,用户可以发送一个请求将应用的监控功能关闭

可以在官网中查看

Production-ready Features (spring.io)

Actuator 提供了十几个接口,具体如下表所示

  • /actuator/health:获取应用程序的健康状态信息。应用程序可以通过实现HealthIndicator接口来自定义健康检查逻辑。
  • /actuator/info:获取应用程序的自定义信息。应用程序可以通过实现InfoContributor接口来向/info端点添加额外的信息。
  • /actuator/metrics:获取应用程序的度量指标信息。应用程序可以通过实现MeterBinder接口来向/metrics端点添加自定义度量指标。
  • /actuator/trace:获取应用程序的HTTP请求跟踪信息。
  • /actuator/beans:获取应用程序中所有的Spring Bean信息。
  • /actuator/mappings:获取应用程序中所有的请求映射信息。
  • /actuator/env:获取应用程序的环境变量和配置属性信息。
  • /actuator/loggers:获取应用程序的日志配置信息。
  • /actuator/threaddump:获取应用程序的线程信息。
  • /actuator/scheduledtasks:获取应用程序中所有的定时任务信息。
  • /actuator/httptrace:获取应用程序的HTTP请求跟踪信息(包括请求和响应的详细信息)。
  • /actuator/sessions:获取应用程序的会话信息(仅适用于基于Spring Session的应用程序)。

以上接口中,/actuator/health、/actuator/info和/actuator/metrics是最常用的。它们可以为应用程序提供健康状态、自定义信息和度量指标等重要信息,对于应用程序的运维和监控非常有帮助。其他接口则可以提供更详细的信息,用于排查问题和调试应用程序。
 

2、暴露端点

默认端点是无法访问的,我么需要配置开启

如下

 

management:
  endpoints:
    web:
      exposure:
        include: "*"
    jmx:
      exposure:
        include: "*"

访问http://localhost/actuator接口查看暴露出来的端点

 

3、路径映射

默认情况下所有端点都暴露在“/actuator”路径下,也可以改/actuator的路徑,可以定成自己想要的:

#原本內建的/actuator/xxx改成/manage/xxx,可以用來防止被其他人猜到
management.endpoints.web.base-path=/manage
 
#同时可以将health修改成healthcheck
management.endpoints.web.path-mapping.health=healthcheck

4、管理端口调整

#指定端口,默认跟server.port一样,可以防止被其他人猜到
management.server.port=10111

 5、端点响应缓存

对于一些不带参数的端点请求会自动进行缓存,我们可以通过如下方式配置缓存时间,下面配置表示 beans 端点的缓存时间为 100s

management.endpoint.beans.cache.time-to-live=100s

三、端点参数详解

1、/health 端点

/health配置

当我们开启health的健康端点时,我们能够查到应用健康信息是一个汇总的信息,访问
http://127.0.0.1:10111/actuator/health时,我们获取到的信息是{"status":"UP"},status的值还有可能是 DOWN。

要想查看详细的应用健康信息需要配置:

management.endpoint.health.show-details=always
该属性可以使用以下值之一进行配置:

never:不展示详细信息,up或者down的状态,默认配置
when-authorized:详细信息将会展示给通过认证的用户。授权的角色可以通过management.endpoint.health.roles配置
always:对所有用户暴露详细信息


按照上述配置,配置成always之后,我们启动项目再次访问
http://127.0.0.1:10111/actuator/health,获取的信息如下

{
    "status": "UP",
    "details": {
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 250685575168,
                "free": 172252426240,
                "threshold": 10485760
            }
        },
        "redis": {
            "status": "UP",
            "details": {
                "version": "3.2.11"
            }
        },
        "db": {
            "status": "UP",
            "details": {
                "database": "Oracle",
                "hello": "Hello"
            }
        }
    }
}

从上面的应用的详细健康信息发现,健康信息包含磁盘空间、redis、DB,启用监控的这个spring boot应用确实是连接了redis和oracle DB,actuator就自动给监控起来了,确实是很方便、很有用。

/health端点有很多自动配置的健康指示器:如redis、rabbitmq、db等组件。当你的项目有依赖对应组件的时候,这些健康指示器就会被自动装配,继而采集对应的信息。

如上面的 diskSpace 节点信息就是DiskSpaceHealthIndicator 在起作用。

 

上述截图取自官方文档。

当如上的组件有一个状态异常,应用服务的整体状态即为down。我们也可以通过配置禁用某个组件的健康监测。

management.health.mongo.enabled: false
或者禁用所有自动配置的健康指示器:

management.health.defaults.enabled: false

/health原理


Spring boot的健康信息都是从ApplicationContext中的各种HealthIndicator Beans中收集到的,Spring boot框架中包含了大量的HealthIndicators的实现类,当然你也可以实现自己认为的健康状态。

默认情况下,最终的spring boot应用的状态是由HealthAggregator汇总而成的,汇总的算法是:

  1. 设置状态码顺序:setStatusOrder(Status.DOWN, Status.OUT_OF_SERVICE, Status.UP, Status.UNKNOWN)。
  2. 过滤掉不能识别的状态码。
  3. 如果无任何状态码,整个spring boot应用的状态是 UNKNOWN。
  4. 将所有收集到的状态码按照 1 中的顺序排序。
  5. 返回有序状态码序列中的第一个状态码,作为整个spring boot应用的状态。

源代码请参见:
org.springframework.boot.actuate.health.OrderedHealthAggregator。
 

Spring boot框架自带的 HealthIndicators 目前包括:

 

你可以通过
management.health.defaults.enabled这个配置项将它们全部禁用掉,也可以通过
management.health.xxxx.enabled将其中任意一个禁用掉。

自定义 HealthIndicator


有时候需要提供自定义的健康状态检查信息,你可以通过实现HealthIndicator的接口来实现,并将该实现类注册为spring bean。

你需要实现其中的health()方法,并返回自定义的健康状态响应信息,该响应信息应该包括一个状态码和要展示详细信息。

例如,下面就是一个接口HealthIndicator的实现类:

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
 
@Component
public class MyHealthIndicator 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();
    }
 
}

 

另外,除了Spring boot定义的几个状态类型,我们也可以自定义状态类型,用来表示一个新的系统状态。

在这种情况下,你还需要实现接口 HealthAggregator ,或者通过配置
management.health.status.order 来继续使用HealthAggregator的默认实现。

例如,在你自定义的健康检查HealthIndicator的实现类中,使用了自定义的状态类型FATAL,为了配置该状态类型的严重程度,你需要在application的配置文件中添加如下配置:

management.health.status.order=FATAL, DOWN, OUT_OF_SERVICE, UNKNOWN, UP
在做健康检查时,响应中的HTTP状态码反应了整体的健康状态,(例如,UP 对应 200, 而 OUT_OF_SERVICE 和 DOWN 对应 503)。

同样,你也需要为自定义的状态类型设置对应的HTTP状态码,例如,下面的配置可以将 FATAL 映射为 503(服务不可用):

management.health.status.http-mapping.FATAL=503
如果你需要更多的控制,你可以定义自己的 HealthStatusHttpMapper bean。

下面是内置健康状态类型对应的HTTP状态码列表:

2、/metrics 端点

查看所有可追踪的度量

/metrics端点用来返回当前应用的各类重要度量指标,比如:内存信息、线程信息、垃圾回收信息、tomcat、数据库连接池等。

 

{
  "names": [
    "hikaricp.connections",
    "hikaricp.connections.acquire",
    "hikaricp.connections.active",
    "hikaricp.connections.creation",
    "hikaricp.connections.idle",
    "hikaricp.connections.max",
    "hikaricp.connections.min",
    "hikaricp.connections.pending",
    "hikaricp.connections.timeout",
    "hikaricp.connections.usage",
    "jvm.buffer.count",
    "jvm.buffer.memory.used",
    "jvm.buffer.total.capacity",
    "jvm.classes.loaded",
    "jvm.classes.unloaded",
    "jvm.gc.live.data.size",
    "jvm.gc.max.data.size",
    "jvm.gc.memory.allocated",
    "jvm.gc.memory.promoted",
    "jvm.gc.pause",
    "jvm.memory.committed",
    "jvm.memory.max",
    "jvm.memory.used",
    "jvm.threads.daemon",
    "jvm.threads.live",
    "jvm.threads.peak",
    "jvm.threads.states",
    "logback.events",
    "process.cpu.usage",
    "process.start.time",
    "process.uptime",
    "system.cpu.count",
    "system.cpu.usage",
    "tomcat.cache.access",
    "tomcat.cache.hit",
    "tomcat.global.error",
    "tomcat.global.received",
    "tomcat.global.request",
    "tomcat.global.request.max",
    "tomcat.global.sent",
    "tomcat.servlet.error",
    "tomcat.servlet.request",
    "tomcat.servlet.request.max",
    "tomcat.sessions.active.current",
    "tomcat.sessions.active.max",
    "tomcat.sessions.alive.max",
    "tomcat.sessions.created",
    "tomcat.sessions.expired",
    "tomcat.sessions.rejected",
    "tomcat.threads.busy",
    "tomcat.threads.config.max",
    "tomcat.threads.current",
    "zipkin.reporter.messages",
    "zipkin.reporter.messages.total",
    "zipkin.reporter.queue.bytes",
    "zipkin.reporter.queue.spans",
    "zipkin.reporter.spans",
    "zipkin.reporter.spans.dropped",
    "zipkin.reporter.spans.total"
  ]
}

各个指标说明如下:

 

查看某个度量的详细信息

不同于1.x,Actuator在这个界面看不到具体的指标信息,只是展示了一个指标列表。为了获取到某个指标的详细信息,我们可以请求具体的指标信息,像这样:

http://localhost:8080/actuator/metrics/{MetricName}
比如我访问
/actuator/metrics/jvm.memory.max,返回信息如下:

你也可以用query param的方式查看单独的一块区域。比如你可以访问
/actuator/metrics/jvm.memory.max?tag=id:Metaspace。结果就是:

 

添加自定义统计指标

除了使用 metrics 端点默认的这些统计指标外,我们还可以实现自定义统计指标。Metrics 提供 4 种基本的度量类型:Gauge、Counter、Timer、Summary。下面分别进行介绍。

 

1,Gauge(计量器)

Gauge(计量器)是最简单的度量类型,只有一个简单的返回值,他用来记录一些对象或者事物的瞬时值。

(1)假设我们在一个 Contoller 使用一个类型为 Gauge 的计数器来记录一个数值:

@RestController
public class HelloController { 
    @GetMapping("/hello")
    public void hello() {
        Metrics.gauge("user.test.gauge", 3);
    }
}

(2)通过 /actuator/metrics 接口可以看到我们自定义的这个指标:

 

 (3)假设我们访问了 /hello 接口后,再次通过
/actuator/metrics/user.test.gauge 这个自定义度量的消息信息,显示如下:

2,Counter(计数器)

Counter(计数器)简单理解就是一种只增不减的计数器。它通常用于记录服务的请求数量、完成的任务数量、错误的发生数量等等。

(1)为方便使用首先我们自定义一个计数器服务:

@Service
public class MyCounterService {
    static final Counter userCounter = Metrics.counter("user.counter.total", "services", "demo"); 
    public void processCollectResult() {
        userCounter.increment(1D);
    }
}

(2)然后增加一个 controller,触发这个服务: 

@RestController
public class HelloController {
 
    @Autowired
    MyCounterService myCounterService;
 
    @GetMapping("/hello")
    public void hello() {
        myCounterService.processCollectResult();
    }
}

 (3)通过 /actuator/metrics 接口可以看到我们自定义的这个指标:

(4)假设我们访问了 3 次 /hello 接口,再次通过
/actuator/metrics/user.counter.total 这个自定义度量的消息信息,显示如下:

 

3,Timer(计时器)

Timer(计时器)可以同时测量一个特定的代码逻辑块的调用(执行)速度和它的时间分布。

简单来说,就是在调用结束的时间点记录整个调用块执行的总时间,适用于测量短时间执行的事件的耗时分布,例如消息队列消息的消费速率。

(1)假设我们在一个 Contoller 使用 Timer 来记录某个方法的执行时长:

注意:在实际生产环境中,可以通过 spring-aop 把记录方法耗时的逻辑抽象到一个切面中,这样就能减少不必要的冗余的模板代码。
 

@RestController
public class HelloController {
 
    private Timer timer = Metrics.timer("user.test.timer","timer", "timersample");
 
    @GetMapping("/hello")
    public void hello() {
 
        // 执行createOrder方法并记录执行时间
        timer.record(() -> createOrder());
    }
 
    //模拟方法耗时
    private void createOrder() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
        }
    }
}

 (2)假设我们访问了 3 次 /hello 接口,再次通过
/actuator/metrics/user.test.timer 这个自定义度量的消息信息,显示如下:

4,Summary(摘要)

Summary(摘要)用于跟踪事件的分布。它类似于一个计时器,但更一般的情况是,它的大小并不一定是一段时间的测量值。

在 micrometer 中,对应的类是 DistributionSummary,它的用法有点像 Timer,但是记录的值是需要直接指定,而不是通过测量一个任务的执行时间。

(1)假设我们在一个 Contoller 使用 Summary 来连续记录三次值:
 

@RestController
public class HelloController {
 
    private DistributionSummary summary = Metrics.summary("user.test.summary","summary", "summarysample");
 
    @GetMapping("/hello")
    public void hello() {
        summary.record(2D);
        summary.record(3D);
        summary.record(4D);
    }
}

 (2)假设我们访问 /hello 接口后,再次通过
/actuator/metrics/user.test.summary 这个自定义度量的消息信息,显示如下:

3、/loggers 端点

查看日志等级

/loggers 端点暴露了我们程序内部配置的所有logger的信息。我们访问/actuator/loggers可以看到:

 

你也可以通过下述方式访问单独一个logger:

http://localhost:8080/actuator/loggers/{name}

比如我现在访问 root logger,
http://localhost:8080/actuator/loggers/root:


{
    "configuredLevel": "INFO",
    "effectiveLevel": "INFO"
}

改变运行时日志等级

/loggers端点能够动态修改你的日志等级。

比如,我们可以通过以下几种方式来修改 root logger的日志等级。我们只需要发起一个URL 为
http://localhost:8080/actuator/loggers/root的POST请求,POST报文如下:
 

{
   "configuredLevel": "DEBUG"
}

 1、使用工具修改:

2、使用浏览器修改:

先在chrome浏览器中,按F12打开console(控制台);然后执行以下脚本(url参数根据自己需求进行修改),回车执行。

fetch(new Request('http://localhost:8080/masl/actuator/loggers/ROOT',{
method:'POST',
headers: {'Content-Type': 'application/json;charset=UTF-8'},
body:"{\"configuredLevel\": \"DEBUG\"}"
})).then((resp)=>{console.log(resp)})

 

3、使用shell脚本修改:

curl -X "POST" "http://localhost:8080/masl/actuator/loggers/ROOT" -H "Content-Type: application/json;charset=UTF-8" -d '{"configuredLevel": "DEBUG"}'


仔细想想,这个功能是不是非常有用。还可以只修改某个类的日志级别(把上面的ROOT替换成类的全路径,如:
com.zat.asl.MaslApplication)

如果在生产环境中,你想要你的应用输出一些Debug信息以便于你诊断一些异常情况,你只需要按照上述方式就可以修改,而不需要重启应用。

4、/info 端点

/info端点可以用来展示应用信息,主要包含三大类:自定义信息、Git 信息、以及项目构建信息。下面主要介绍自定义信息。

(1)自定义信息可以在 application.properties 配置文件中添加,这些以 info 开头的信息将在 info 端点中显示出来:
 

info.app.name=actuator-test-demo
info.app.encoding=UTF-8
info.app.java.source=1.8
info.app.java.target=1.8

启动项目,访问
http://localhost:8080/actuator/info:

{
    "app": {
        "encoding": "UTF-8",
        "java": {
            "source": "1.8.0_131",
            "target": "1.8.0_131"
        },
        "name": "actuator-test-demo"
    }
}

 (2)我们也可以通过 Java 代码自定义信息,只需要将自定义类继承自 InfoContributor,然后实现该类中的 contribute 方法即可:

@Component
public class MyInfo implements InfoContributor {
    @Override
    public void contribute(Info.Builder builder) {
        Map<String, String> info = new HashMap<>();
        info.put("name", "航歌");
        info.put("email", "service@hangge.com");
        builder.withDetail("author", info);
    }
}

 

5、/beans 端点

/beans端点会返回Spring 容器中所有bean的别名、类型、是否单例、依赖等信息。

访问
http://localhost:8080/actuator/beans,返回如下:

 

6、/heapdump 端点

访问:
http://localhost:8080/actuator/heapdump会自动生成一个 Jvm 的堆文件 heapdump。我们可以使用 JDK 自带的 Jvm 监控工具 VisualVM 打开此文件查看内存快照。

 

7、/threaddump 端点

这个端点我个人觉得特别有用,方便我们在日常定位问题的时候查看线程的情况。 主要展示了线程名、线程ID、线程的状态、是否等待锁资源、线程堆栈等信息。就是可能查看起来不太直观。

访问
http://localhost:8080/actuator/threaddump返回如下:

这个端点属于操作控制类端点,可以优雅关闭 Spring Boot 应用。要使用这个功能首先需要在配置文件中开启:

management.endpoint.shutdown.enabled=true
由于 shutdown 接口默认只支持 POST 请求,我们启动Demo项目,发起POST请求:

curl -X "POST" "http://localhost:8080/actuator/shutdown"
返回信息:
 

{
    "message": "Shutting down, bye..."
}

 

然后应用程序被关闭。类似停服的操作还有很多,比如restart、pause等。可根据具体版本进行配置。

由于开放关闭应用的操作本身是一件非常危险的事,所以真正在线上使用的时候,我们需要对其加入一定的保护机制,

比如:定制Actuator的端点路径、整合Spring Security进行安全校验等。(不是特别必要的话,这个端点不用开)。

定制Actuator的端点路径和端口:

  • management.endpoints.web.base-path 自定义shutdown的请求路径;
  • management.server.address 设置为本地ip,防止远程访问该连接进行关闭服务;
  • management.server.port 自定义shutdown请求路径的端口号;

调整后的配置文件如下:

management:
  endpoint:
    shutdown:
      enabled: true
  endpoints:
    web:
      exposure:
        include: '*'
    jmx:
      exposure:
        include: '*'
  server:
    # 自定义端口
    port: 8888
    # 不允许远程管理连接,安全性考虑
    address: 127.0.0.1

 

四、自定义端点

默认的端点虽然可以满足大多数的需求,但一些特殊的需求还是需要能够支持自定义端点的。自定义 Endpoint 端点,只需要在我们的新建Bean上使用注解即可

Spring Boot2x 开始,Actuator支持CRUD模型,而不是旧的RW(读/写)模型

  • @Endpoint 同时支]MX和http
  • @JmxEndpoint 只支持]MX技术
  • @WebEndpoint 只支持http

通过在一个端点类(必须是Spring Bean)上添加上面其中一个来表明该类是一个端点类。在类的方法使用@ReadOperation,@WriteOperation或@DeleteOperation,这分别会映射到Http中的GET、POST、DELETE(对http来说)

@Component
@Endpoint(id = "my")  id就是访问路径
public class EndpointCustom {
 
   @ReadOperation
   public String endpointCustomRead(String content) {
      return "请求的内容: " + content;
   }
 
   @WriteOperation
   public String endpointCustomWrite(String content) {
      return "写的内容: " + content;
   }
 
   @DeleteOperation
   public String endpointCustomDelete(String content) {
      return "删除的内容: " + content;
   }
 
}

对应GET请求:

curl -X GET http://localhost:8080/actuator/my?content=endpointGet
执行之后,会返回信息“请求的内容: endpointGet”。

同样的POST请求为:

curl -X POST http://localhost:8080/actuator/my?content=endpointPost
DELETE请求为:

curl -X DELETE http://localhost:8080/actuator/my?content=endpointDELETE
上面只是简单自定义实例,根据具体的业务场景,可以定义更加丰富的端点实现。


当然对于对某个端点传递参数,而Actuator 专门提供了一个 @Seletor 注解标识输入参数,通过restful请求方式传递参数

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值