Java微服務監控及與普羅米集成

一、    背景說明

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」,可以實現與普羅米修斯的對接。

Tags: