在生產環境中,需要實時或定期監控服務的可用性,spring-Boot的Actuator 功能提供了很多監控所需的接口。
Actuator是Spring Boot提供的對應用系統的自省和監控的集成功能,可以對應用系統進行配置查看、健康檢查、相關功能統計等,一般運維人員使用多些,開發了解即可。
使用該功能步驟
我們這里監控03-springboot-web程序
項目名稱:038-springboot-actuator
1.在項目pom.xml中添加SSM需要的依賴
<!--MyBatis集成SpringBoot框架的起步依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!--連接MySQL的驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 加載spring boot redis包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--SpringBoot項目內嵌tomcat對jsp的解析包-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
2.在pom文件中添加Actuator需要的依賴
<!--Spring Boot Actuator依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
3.編寫集成SSM在application.properties的配置
#設置內嵌Tomcat端口號
server.port=9090
#設置項目上下文根
server.servlet.context-path=/038-springboot-actuator
#配置jsp的前/后綴
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
#配置連接MySQL數據庫信息
spring.datasource.url=jdbc:mysql://192.168.92.134:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
#配置redis連接信息(單機模式)
spring.redis.host=192.168.92.134
spring.redis.port=6379
spring.redis.password=123456
4.在application.properties或application.yml配置文件中指定監控的HTTP端口及路徑
我這里沒有進行配置
• #服務運行的端口
server.port=8080
server.servlet.context-path=/038-springboot-actuator
• #actuator監控的端口(端口可配可不配,如果不配置,則使用和server.port相同的端口)
management.server.port=8100
• #actuator監控的訪問上下文根路徑(路徑可配可不配,如果不配置,則使用和server.context-path相同的路徑)
management.server.servlet.context-path=/038-springboot-actuator
5.在application.properties或application.yml配置文件中設置開啟所有的端口
#默認只開啟了health和info,設置為*,則包含所有的web入口端點
management.endpoints.web.exposure.include=*
6.啟動MySQL
7.啟動Redis
8.啟動038-springboot-actuator
① 瀏覽器訪問http://localhost:9090/actuator/health
② 瀏覽器訪問http://localhost:9090/actuator/info
默認沒有內容
需要自己在application.properties配置文件中添加信息,需要以info開頭,后面的內容可以自己設定,一般配置項目的版權等信息,例如
#配置項目版權相關信息
[email protected]
info.contact.phone=010-84846003
配置完畢后,重啟項目再進行訪問
Actuator提供的主要功能
HTTP方法 |
路徑 |
描述 |
---|---|---|
GET |
/configprops |
查看配置屬性,包括默認配置 |
GET |
/beans |
查看Spring容器目前初始化的bean及其關系列表 |
GET |
/env |
查看所有環境變量 |
GET |
/mappings |
查看所有url映射 |
GET |
/health |
查看應用健康指標 |
GET |
/info |
查看應用信息 |
GET |
/metrics |
查看應用基本指標 |
GET |
/metrics/{name} |
查看具體指標 |
JMX |
/shutdown |
關閉應用 |
shutdown的使用
注意:/shutdown不能直接在瀏覽器中訪問
• 先在pom.xml文件中配置
# 啟用關閉springboot的服務
# 關閉SpringBoot服務是否可用,true讓其關閉服務可用,默認為不可用
management.endpoint.shutdown.enabled=true
• 雙擊打開jconsole
• 選擇Spring Boot進程,進行連接管理
• 點擊shutdown,可關閉Spring Boot服務