1. 程式人生 > 實用技巧 >搭建prometheus+grafana監控SpringBoot應用入門

搭建prometheus+grafana監控SpringBoot應用入門

搭建prometheus+grafana監控SpringBoot應用入門

1. springBoot 應用準備

pom.xml依賴

      
      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--prometheus-->
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
            <version>1.0.3</version>
        </dependency>

並且主動向prometheus 上報application名.


   /**
     * 上報application 到 Prometheus
     */
    @Bean
    MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
        return registry -> registry.config().commonTags("application", "yourappName");
    }

SpringBoot actuator端開啟 (自行調整,我這裡全部開啟):


management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always
    prometheus:
      enabled: true

最好啟動一下檢視端點暴露的情況,尤其檢查 /actuator/prometheus 是否成功暴露

2. 下載並安裝prometheus

最新下載地址 : https://prometheus.io/download/

配置prometheus.yml(安裝完成後的目錄下面有)

重點是配置好基礎的job_name,metrics_path,還有應用的ip和埠號,例如 :


scrape_configs:
  - job_name: 'prometheus'
    static_configs:
    - targets: ['localhost:9090']
    
  - job_name: 'test-application'
    metrics_path: '/actuator/prometheus'
    static_configs:
    - targets: ['localhost:9527']

配置好之後,可以啟動prometheus,並且訪問prometheus,預設訪問地址 http://localhost:9090

此時可以看到prometheus的情況,點選Status的targets,檢視應用例項情況

3. 下載並安裝grafana(windows的安裝過程中最好關閉防毒軟體,可能導致安裝失敗)

最新下載地址 : https://grafana.com/grafana/download

執行啟動grafana,預設訪問地址 : http://localhost:3000, 預設使用者名稱/密碼 admin/admin

配置datasource(Configuration裡面),選擇Prometheus,配置好prometheus,本機執行的prometheus,則access選擇Server即可。然後點選Save&Test

配置Dashboard,可以定製,可以自選(種類繁多,花樣不勝列舉),這裡直接選造好的SpringBoot,Dashboard匯入(拿來即用)

直接位址列輸入
https://grafana.com/grafana/dashboards/6756 或者 6756,然後點選load。

此時點選Dashboard :