Spring Boot Actuator微服务服务监控

作者:xcbeyond
疯狂源自梦想,技术成就辉煌!微信公众号:《程序猿技术大咖》号主,专注后端开发多年,拥有丰富的研发经验,乐于技术输出、分享,现阶段从事微服务架构项目的研发工作,涉及架构设计、技术选型、业务研发等工作。对于Java、微服务、数据库、Docker有深入了解,并有大量的调优经验。

1、Spring Boot Actuator介绍
     Spring Boot Actuator是Spring Boot中一个比较强大的特性功能,能够帮助你监控和管理你的应用程序,通过提供的restful api接口来监管、审计、收集应用的运行情况,针对微服务而言它是必不可少的一个组件。

有如下特性:

Endpoints
  Spring Boot Actuator的核心部分,它用来监视应用程序及交互,spring-boot-actuator中已经内置了非常多的Endpoints(health、info、beans、httptrace、shutdown)等等,同时也允许我们自己扩展自己的端点。例如:health端点提供了应用程序的基本健康信息。

    使用了actuator后,并不代表所有内置的端点都能够访问,启用了并不代表可以直接访问,还需要配置参数(management.endpoints.web.exposure.include)将其暴露出来。

内置Endpoints
 

Metrics 
    Spring Boot Actuator通过集成Micrometer来提供一些监控指标标准,详细可参考:https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-metrics.html

Audit 
     Spring Boot Actuator有一个比较灵活的审计框架,那就是Audit,可以将事件发布到AuditEventRepository。一旦Spring Security正在运行,它会默认自动发布身份验证事件。这对于认证审计非常有用,并且还可以基于身份验证失败实施锁定策略,或自定义扩展一些审计功能,你可以实现已提供的接口AbstractAuthenticationAuditListener 和AbstractAuthorizationAuditListener。

 

     看完上面这些特性,是不是有一种马上上手尝试一下的冲动了吧。Spring Boot Actuator将会为你的服务监控和管理提供很多的便利,不必闭门造车了。

2、开发配置
   导入依赖包
   在pom.xml中添加spring-boot-starter-actuator的依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
属性配置
      在application.yml文件中配置actuator的相关配置,其中info开头的属性,就是访问info端点中显示的相关内容,值得注意的十spring boot2.x中,默认只开放了info、health两个端点,其余的需要自己通过配置management.endpoints.web.exposure.include属性来加载(有include自然就有exclude)。如果想单独操作某个端点可以使用management.endpoint.端点.enabled属性进行启用或者禁用。

info:
  head: head
  body: body
management:
  endpoints:
    web:
      exposure:
        #加载所有的端点,默认只加载了info、health
        include: '*'
  endpoint:
    health:
      show-details: always
    #可以关闭指定的端点
    shutdown:
      enabled: false
3、总结

     Spring Boot Actuator组件作为微服务中服务监控的核心,Spring Boot Admin也是基于这个Actuator开发的,所以当涉及到服务监控相关的,可以优先考虑从Actuator入手。

参考文档:

https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-metrics.html

https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-auditing.html