SpringBoot实现项目健康检查与监控
SpringBoot最主要的特性就是AutoConfig(自动配置),而对于我们这些使用者来说也就是各种starter,
SpringBoot-Actuator也提供了starter,为我们自动配置,在使用上我们只需要添加starter到我们的依赖中,然后启动项目即可。
org.springframework.boot spring-boot-starter-actuator
常用Endpoint
SpringBoot-actuator,提供了许多有用的EndPoint,对SpringBoot应用提供各种监控,下面说一下我常用的EndPoint:
/health应用的健康状态
/configprops获取应用的配置信息,因为SpringBoot可能发布时是单独的Jar包,配置文件可能包含其中,当我们需要检查配置文件时可以使用ConfigpropsEndPoint进行查看一些配置是否正确。
/trace最近几次的http请求信息
HealthEndPoint
当我们访问http://localhost:8088/health时,可以看到HealthEndPoint给我们提供默认的监控结果,包含磁盘检测和数据库检测。
{
"status":"UP",
"diskSpace":{
"status":"UP",
"total":398458875904,
"free":315106918400,
"threshold":10485760
},
"db":{
"status":"UP",
"database":"MySQL",
"hello":1
}
}
其实看SpringBoot-actuator源码,你会发现HealthEndPoint提供的信息不仅限于此,org.springframework.boot.actuate.health包下你会发现ElasticsearchHealthIndicator、RedisHealthIndicator、RabbitHealthIndicator等
也就是HealthEndPoint也提供ES,Redis等组件的健康信息。
自定义Indicator扩展HealthEndPoint
看源码其实磁盘和数据库健康信息就是DiskSpaceHealthIndicator、DataSourceHealthIndicator来实现的,当我们对一些我们自定义的组件进行监控时,我们也可以实现个Indicator:
@Component
publicclassUserimplementsHealthIndicator{
/**
*user监控访问:http://localhost:8088/health
*
*@return自定义Health监控
*/
@Override
publicHealthhealth(){
returnnewHealth.Builder().withDetail("usercount",10)//自定义监控内容
.withDetail("userstatus","up").up().build();
}
}
这时我们再次访问:http://localhost:8088/health这时返回的结果如下,包含了我们自定义的User健康信息。
{
"status":"UP",
"user":{
"status":"UP",
"usercount":10,
"userstatus":"up"
},
"diskSpace":{
"status":"UP",
"total":398458875904,
"free":315097989120,
"threshold":10485760
},
"db":{
"status":"UP",
"database":"MySQL",
"hello":1
}
}
自定义EndPoint
其实除了扩展HealthEndPoint来添加一些健康检查,我们也可以自定定义一些EndPoint来提供程序运行时一些信息的展示:
@Configuration
publicclassEndPointAutoConfig{
@Bean
publicEndpoint
访问http://localhost:8088/customsystem来查看我们自定义的EndPoint,返回结果如下:
{
"username":"xxx",
"userdomain":"DESKTOP-6EAN1H4",
"computername":"DESKTOP-6EAN1H4"
}
我们在为SpringBoot应用添加actuator后,期望的health接口返回结果应该是类似下面的结果:
{
status:"UP",
diskSpace:
{
status:"UP",
total:250182889472,
free:31169568768,
threshold:10485760
},
db:
{
status:"UP",
database:"H2",
hello:1
}
}
如果只是返回了status
{
status:"UP"
}
则需要为应用新增配置,以yml配置文件为例,需要添加如下配置:
management: security: enabled:false endpoints: health: sensitive:false
management.endpoint.health.show-details=always
总结
以上所述是小编给大家介绍的SpringBoot实现项目健康检查与监控,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。