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

6、附錄

如果出現POST、PUT和DELETE方法無法訪問,請增加如下代碼配置。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM