一、 背景說明
Java服務級監控用于對每個應用占用的記憶體、線程池的線程數量、restful調用數量和響應時間、JVM狀态、GC資訊等進行監控,并可将名額資訊同步至普羅米修斯中集中展示和報警。網上類似的文章較多,内容長且時間較舊,本文所寫内容已經過實踐驗證,可快速幫助你實作內建。
二、 監控方案說明
本監控方案僅用于SpringBoot 2項目。通過在服務中引入actuator元件實作與普羅米修斯的內建。由于actuator有一定的安全隐患,本文也着重介紹了如何實作授權通路。
三、 方案詳情
1、引入spring actuator及spring security
Actuator用于收集微服務的監控名額包括記憶體使用、GC、restful接口調用時長等資訊。為避免敏感資訊洩露的風險,還需要同時使用spring security架構以實作通路actuator端點時的授權控制。“micrometer-registry-prometheus”用于将您的微服務暴露為“exportor”,可直接對接普羅米修斯。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.8.1</version>
</dependency>
2、配置檔案(application.yml)增加應用名稱
spring:
application:
name: your service name
“name”節點的值需要根據目前服務的名稱填寫,建議規則如下:小于32字元長度;全小寫;單詞間使用“-”分隔。
3、配置檔案中增加actuator配置
建議将下面配置放在二級配置檔案(application-x,例:線上配置檔案“application-prod”)中。配置資訊的“include”節點建議僅暴露“prometheus”節點。
#name和password為您自定義的資訊
spring:
security:
user:
name: ***
password: ***
management:
server:
port: 1234 #給actuator一個自定義端口,建議與服務的端口進行區分
metrics:
tags:
application: ${spring.application.name}
endpoints:
web:
base-path: /${spring.application.name}/application-monitor #安全起見,此處使用自定義位址
exposure:
include: prometheus #安全起見,僅暴露prometheus一個端點
4、配置spring security
為實作actuator端點通路授權,需要在啟動檔案(即包含“static void main”方法的檔案)的同級任意目錄中建立一個名為“SecurityConfig .java”的java檔案,并将下列代碼複制到類中
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.httpBasic()
.and()
.authorizeRequests()
//application-monitor為3小節本配置檔案中自定義的actuator端點url,此處代碼表示當通路actuator端點時,需要進行登入。使用者名和密碼參看3小節配置
.antMatchers("/**/application-monitor/**").authenticated()
.anyRequest().permitAll(); //其它業務接口不用登入
}
}
5、驗證結果
配置完成後啟動服務。通路服務中的查詢類和指令類業務接口,應與引入“actuator”和“spring security”前一緻。通路“ip:1234/{your service name}/application-monitor/prometheus”,應顯示登入界面,如下圖所示。
輸入3小節中“spring.security.user”節點中的使用者名與密碼,顯示如下界面表示配置成功。需要注意:務必保證測試結果與上述說明一緻,以避免服務正常的restful接口無法被通路。
配置成功後,您的服務就變成了一個标準的“exportor”,可以實作與普羅米修斯的對接。
6、附錄
如果出現POST、PUT和DELETE方法無法通路,請增加如下代碼配置。