天天看点

Spring Boot应用的健康监控

在之前的系列文章中我们学习了如何进行spring boot应用的功能开发,以及如何写单元测试、集成测试等,然而,在实际的软件开发中需要做的不仅如此:还包括对应用程序的监控和管理。

正如飞行员不喜欢盲目飞行,程序员也需要实时看到自己的应用目前的运行情况。如果给定一个具体的时间,我们希望知道此时cpu的利用率、内存的利用率、数据库连接是否正常以及在给定时间段内有多少客户请求等指标;不仅如此,我们希望通过图表、控制面板来展示上述信息。最重要的是:老板和业务人员希望看到的是图表,这些比较直观易懂。

首先,这篇文章讲介绍如何定制自己的health indicator。

在pom文件中添加spring-boot-starter-actuator依赖

Spring Boot应用的健康监控

acatuator库提供监控信息

除了/health可以访问,其他的endpoints也可以访问,例如/info:首先在application.properties文件中添加对应的属性值,符号@包围的属性值来自pom.xml文件中的元素节点。

要获取配置文件中的节点值,需要在pom文件中进行一定的配置,首先在<build>节点里面添加:

然后在<plugins>节点里面增加对应的插件:

Spring Boot应用的健康监控

http://localhost:8080/info

在db-count-starter/src/main/com/test/bookpubstarter目录下创建dbcounthealthindicator.java文件

最后,还需要注册刚刚创建的健康监控器,在dbcountautoconfiguration.java中增加如下定义:

Spring Boot应用的健康监控

自定义的health indicator

spring boot autuator这个库包括很多自动配置,对外开放了很多endpoints,通过这些endpoints可以访问应用的运行时状态:

Spring Boot应用的健康监控

tomcatsslconnector对应的属性值

/beans,这个endpoint列出所有由spring boot创建的bean。

Spring Boot应用的健康监控

/beans显示所有spring boot创建的bean

/mapping,这个endpoint显示当前应用支持的url映射,该映射关系由handlermapping类维护,通过这个endpoint可以查询某个url的路由信息。

Spring Boot应用的健康监控

/mappings查看url映射

/health提供应用程序的健康状态,或者是某个核心模块的健康状态。

/metrics,这个endpoint显示metrics 子系统管理的信息,后面的文章会详细介绍它。

上述各个endpoint是spring boot actuator提供的接口和方法,接下来看看我们自己定制的healthindicator,我们只需要实现healthindicator接口,spring boot会收集该接口的实现,并加入到/health这个endpoint中。

在我们的例子中,我们为每个crudrepository实例都创建了一个healthindicator实例,为此我们创建了一个compositehealthindicator实例,由这个实例管理所有的dbhealthindicator实例。作为一个composite,它会提供一个内部的层次关系,从而可以返回json格式的数据。

代码中的healthaggregator实例的作用是:它维护一个map,告诉compositehealthindicator如何决定所有healthindicator代表的整体的状态。例如,除了一个repository返回down其他的都返回up,这时候这个composite indicator作为一个整体应该返回up还是down,healthaggregator实例的作用就在这里。

spring boot使用的默认的healthaggregator实现是orderedhealthaggregator,它的策略是手机所有的内部状态,然后选出在down、out_of_service、up和unknown中间具有最低优先级的那个状态。这里使用策略设计模式,因此具体的状态判定策略可以改变和定制,例如我们可以创建定制的healthaggregator:

最后需要考虑下安全问题,通过这些endpoints暴露出很多应用的信息,当然,spring boot也提供了配置项,可以关闭指定的endpoint——在application.properties中配置<name>.enable=false;

可以在防火墙上屏蔽掉不是/admin/*的endpoints访问请求,更进一步,利用spring security可以配置验证信息,这样要访问当前应用的endpoints必须使用用户名和密码登陆。

<a href="https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html" target="_blank">endpoints</a>

<a href="http://www.javabeat.net/spring-boot-actuator/" target="_blank">complete guide for spring boot actuator</a>