Spring Boot + Prometheus + Grafana 打造視覺化監控,一目瞭然!
作者:煙味i
連結:https://www.cnblogs.com/2YSP/p/12827487.html
一、背景
Spring Boot 的應用監控方案比較多,SpringBoot + Prometheus + Grafana 是目前比較常用的方案之一。
它們三者之間的關係大概如下圖:
二、開發SpringBoot應用
首先,建立一個SpringBoot專案,pom檔案如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- https://mvnrepository.com/artifact/io.prometheus/simpleclient_spring_boot --> <dependency> <groupId>io.prometheus</groupId> <artifactId>simpleclient_spring_boot</artifactId> <version>0.8.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
推薦一個 Spring Boot 基礎教程及實戰示例:
https://github.com/javastacks/spring-boot-best-practice
注意: 這裡的SpringBoot版本是1.5.7.RELEASE,之所以不用最新的2.X是因為最新的simpleclient_spring_boot只支援1.5.X,不確定2.X版本的能否支援。
MonitorDemoApplication啟動類增加註解
package cn.sp; import io.prometheus.client.spring.boot.EnablePrometheusEndpoint; import io.prometheus.client.spring.boot.EnableSpringBootMetricsCollector; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @EnablePrometheusEndpoint @EnableSpringBootMetricsCollector @SpringBootApplication public class MonitorDemoApplication { public static void main(String[] args) { SpringApplication.run(MonitorDemoApplication.class, args); } }
配置檔案application.yml
server: port: 8848 spring: application: name: monitor-demo security: user: name: admin password: 1234 basic: enabled: true # 安全路徑列表,逗號分隔,此處只針對/admin路徑進行認證 path: /admin # actuator暴露介面的字首 management: context-path: /admin # actuator暴露介面使用的埠,為了和api介面使用的埠進行分離 port: 8888 security: enabled: true roles: SUPERUSER
測試程式碼TestController
@RequestMapping("/heap/test")
@RestController
public class TestController {
public static final Map<String, Object> map = new ConcurrentHashMap<>();
@RequestMapping("")
public String testHeapUsed() {
for (int i = 0; i < 10000000; i++) {
map.put(i + "", new Object());
}
return "ok";
}
}
這裡的邏輯就是在請求這個介面後,建立大量物件儲存到map中增加堆記憶體使用量,方便後面測試郵件報警。
啟動專案後,可以在IDEA中看到有很多Endpoints,如圖:
開始我的IDEA是不顯示這個Endpoints,後來發現是我使用的idea版本太老了,還是2017.1的,
而這個需要 idea2017.2版本以上才能看到。
後來只好重新下載安裝,弄了好久。。。。
啟動完畢,訪問http://localhost:8888/admin/prometheus就可以看到服務暴露的那些監控指標了。
注意:
由於開啟了安全認證,所以訪問這個URL的需要提示輸入賬號/密碼,如果提示404請檢查下你的請求地址是否正確,如果不設定management.context-path則預設地址是http://ip:port/prometheus
三、安裝Prometheus
下載地址點選這裡,本文下載的是Windows版本prometheus-2.17.2.windows-amd64.tar.gz。
解壓後修改prometheus.yml檔案,配置資料採集的目標資訊。
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
# - job_name: 'prometheus'
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
# static_configs:
# - targets: ['localhost:9090']
- job_name: 'monitor-demo'
scrape_interval: 5s # 刮取的時間間隔
scrape_timeout: 5s
metrics_path: /admin/prometheus
scheme: http
basic_auth: #認證資訊
username: admin
password: 1234
static_configs:
- targets:
- 127.0.0.1:8888 #此處填寫 Spring Boot 應用的 IP + 埠號
更多配置資訊請檢視官方文件。
現在可以啟動Prometheus了,命令列輸入:prometheus.exe --config.file=prometheus.yml
訪問http://localhost:9090/targets,檢視Spring Boot採集狀態是否正常。
四、安裝Grafana
下載地址點選這裡,本文用到的是Windows版本grafana-6.3.3.windows-amd64.zip。
解壓後執行bin目錄下的grafana-server.exe啟動,遊覽器訪問http://localhost:3000即可看到登入頁面,預設賬號密碼是admin/admin。
現在開始建立自己的視覺化監控面板。
1.設定資料來源
2. 建立一個Dashboard
3. 填寫採集的指標點
注意: 這裡的指標點不能隨便填,必須是已有的可以在 Prometheus看到。
4.選擇圖表樣式
5.填寫標題描述
最後點選右上角的儲存,輸入Dashboad的名稱即可。
Tips: 這裡的圖表佈局是可以用滑鼠拖動的
五、新增郵件報警
在實際專案中當監控的某的個指標超過閾值(比如CPU使用率過高),希望監控系統自動通過簡訊、釘釘和郵件等方式報警及時通知運維人員,Grafana就支援該功能。
第一步: 點選[Alerting]——>[Notification channels]新增通知通道
建立通道
這裡的Type有很多選項,包括webhook、釘釘等,這裡以郵件為例。
第二步: 郵箱配置
Grafana預設使用conf目錄下defaults.ini作為配置檔案執行,根據官方的建議我們不要更改defaults.ini而是在同級目錄下新建一個配置檔案custom.ini。
以騰訊企業郵箱為例,配置如下:
#################################### SMTP / Emailing #####################
[smtp]
enabled = true
host = smtp.exmail.qq.com:465
user = [email protected]
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
password = XXX
cert_file =
key_file =
skip_verify = true
from_address = [email protected]
from_name = Grafana
ehlo_identity = ininin.com
然後需要重啟Grafana,命令grafana-server.exe -config=E:\file\grafana-6.3.3\conf\custom.ini
第三步: 為指標新增alert
配置預警規則
配置通知方式和資訊
Evaluate every
表示檢測評率,這裡為了測試效果,改為1秒
For
如果警報規則配置了For,並且查詢違反了配置的閾值,那麼它將首先從OK變為Pending。從OK到Pending Grafana不會發送任何通知。一旦警報規則的觸發時間超過持續時間,它將更改為Alerting併發送警報通知。
Conditions
when 表示什麼時間,of 表示條件,is above 表示觸發值
同時,設定了is above後會有一條紅線。
If no data or all values are null
如果沒有資料或所有值都為空,這裡選擇觸發報警
If execution error or timeout
如果執行錯誤或超時,這裡選擇觸發報警
注意: 下一次觸發,比如10秒後,它不會再次觸發,防止報警風暴產生!
第四步: 測試
請求http://localhost:8848/heap/test介面後,記憶體升高大於設定的閾值,然後就收到報警郵件。
這裡圖片沒有顯示出來,搞不懂為什麼。
六、總結
這套監控功能還是挺強大的,就是Prometheus的表示式有點多。
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2022最新版)
4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這才是優雅的方式!!
覺得不錯,別忘了隨手點贊+轉發哦!