spring-boot actuator(監控)配置和使用
阿新 • • 發佈:2018-12-25
在生產環境中,需要實時或定期監控服務的可用性。spring-boot 的actuator(監控)功能提供了很多監控所需的介面。簡單的配置和使用如下:
1、引入依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
如果使用http呼叫的方式,還需要這個依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2、配置:
application.yml中指定監控的HTTP埠(如果不指定,則使用和server相同的埠);指定去掉某項的檢查(比如不監控health.mail):
server:
port: 8082
management:
port: 54001
health:
mail:
enabled: false
3、使用:
檢視health指標:http://localhost:54001/health{"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()方法即可:
程式碼:
@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配置中獲取
info:
app:
name: "@[email protected]" #從pom.xml中獲取
description: "@[email protected]"
version: "@[email protected]"
spring-boot-version: "@[email protected]"
/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