在生產環境中,需要實時或定期監控服務的可用性。spring-boot 的actuator(監控)功能提供了很多監控所需的接口。簡單的配置和使用如下:
1、引入依賴:
1
2
3
4
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-actuator</ artifactId > </ dependency > |
如果使用http調用的方式,還需要這個依賴:
1
2
3
4
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-web</ artifactId > </ dependency > |
2、配置:
application.yml中指定監控的HTTP端口(如果不指定,則使用和server相同的端口);指定去掉某項的檢查(比如不監控health.mail):
1
2
3
4
5
6
7
|
server: port: 8082 management: port: 54001 health: mail: enabled: false |
3、使用:
查看health指標:http://localhost:54001/health
1
|
{"status":"UP","diskSpace":{"status":"UP","total":120031539200,"free":33554337792,"threshold":10485760},"db":{"status":"UP","dataSource1":{"status":"UP","database":"MySQL","hello":1},"dataSource2":{"status":"UP","database":"MySQL","hello":1}}} |
4、自定義指標:
4.1 /health:在某個類中implements HealthIndicator接口,然后實現其中的health()方法即可:
代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@SpringBootApplication @EnableScheduling public class MySpringBootApplication implements HealthIndicator{ private static Logger logger = LoggerFactory.getLogger(MySpringBootApplication. class ); public static void main(String[] args) { SpringApplication.run(MySpringBootApplication. class , args); logger.info( "My Spring Boot Application Started" ); } /** * 在/health接口調用的時候,返回多一個屬性:"mySpringBootApplication":{"status":"UP","hello":"world"} */ @Override public Health health() { return Health.up().withDetail( "hello" , "world" ).build(); } } |
/health 運行結果(注意第二個指標):
{"status":"UP","mySpringBootApplication":{"status":"UP","hello":"world"},"diskSpace":{"status":"UP","total":120031539200,"free":33554337792,"threshold":10485760},"db":{"status":"UP","dataSource1":{"status":"UP","database":"MySQL","hello":1},"dataSource2":{"status":"UP","database":"MySQL","hello":1}}}
4.2 /info:配置如下,可以直接給一個字符串,也可以從pom.xml配置中獲取
1
2
3
4
5
6
|
info: app: name: "@project.name@" #從pom.xml中獲取 description: "@project.description@" version: "@project.version@" spring-boot-version: "@project.parent.version@" |
/info的結果如下:
{"app":{"name":"my-spring-boot","description":"Test Project for Spring Boot","version":"1.0","spring-boot-version":"1.3.6.RELEASE"}}
官網:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready
源代碼參考:https://github.com/xujijun/my-spring-boot
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/clementad/article/details/52045495