Springboot+actuator+prometheus+Grafana整合

2023-06-03 18:00:56

本次範例以Windows範例

推薦到官網去下載:Windows版的應用程式

下載最新版 prometheus-2.37.8.windows-amd64 壓縮包:解壓就行

下載最新版 grafana-9.5.2 壓縮包:解壓就行

準備一個Springboot的專案:

匯入相關的監控依賴


        <!--監控站點開啟-->
        <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.10.5</version>
        </dependency>


        <!--SpringSecurity 安全存取-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

springSecurity的設定

#springSecurity 設定
spring.security.user.name=root
spring.security.user.password=root
spring.security.user.roles=ADMIN

spring-actuator設定

#增加開啟springboot actuator監控的設定
management:
  endpoint:
    shutdown:
      enabled: true # 開啟端點
    health:
      show-details: always # 是否展示健康檢查詳情
  endpoints:
    web:
      exposure:
        include:
          - prometheus
          - health
  metrics:
    tags:
      application: ${spring.application.name}

springSecurity的白名單介面設定-SecurityConfig

package com.gton.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @description:
 * @author: GuoTong
 * @createTime: 2023-06-01 21:44:49
 * @since JDK 1.8 OR 11
 **/

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().and().authorizeRequests()
                .antMatchers("/actuator/**", "/favicon.ico", "/doc.html").permitAll()
                .antMatchers("/static/**").permitAll()
                .antMatchers("/favicon.ico").permitAll()
                // swagger
                .antMatchers("/swagger**/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/**").permitAll()
                .anyRequest().authenticated().and().csrf().disable();    //關閉csrf保護
    }

    /**
     * Description: 忽略一些藉口
     *
     * @author: GuoTong
     * @date: 2023-06-01 21:44:49
     * @return:
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers(
                        "/doc.html",
                        "/swagger-resources/configuration/ui",
                        "/swagger*",
                        "/swagger**/**",
                        "/webjars/**",
                        "/favicon.ico",
                        "/**/*.css",
                        "/**/*.js",
                        "/**/*.png",
                        "/**/*.gif",
                        "/v2/**",
                        "/**/*.ttf",
                        "/actuator/**"
                );
    }
}

springboot的相關的設定


    @Value("${auth.global.enable:false}")
    private boolean enableGlobalAuth;

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }


    /**
     * Description:  新增全域性跨域CORS處理
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 設定允許跨域的路徑
        registry.addMapping("/**")
                //設定允許跨域請求的域名
                .allowedOrigins("http://127.0.0.1:8787")
                // 是否允許證書
                .allowCredentials(true)
                // 設定允許的方法
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 設定允許的header屬性
                .allowedHeaders("*")
                // 跨域允許時間
                .maxAge(3600);
    }


    /**
     * Description: 靜態資源過濾
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //ClassPath:/Static/** 靜態資源釋放
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        //釋放swagger
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        //釋放webjars
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 解決springboot升到2.6.x之後,knife4j報錯
     *
     * @param webEndpointsSupplier        the web endpoints supplier
     * @param servletEndpointsSupplier    the servlet endpoints supplier
     * @param controllerEndpointsSupplier the controller endpoints supplier
     * @param endpointMediaTypes          the endpoint media types
     * @param corsEndpointProperties      the cors properties
     * @param webEndpointProperties       the web endpoints properties
     * @param environment                 the environment
     * @return the web mvc endpoint handler mapping
     */
    @Bean
    public WebMvcEndpointHandlerMapping webMvcEndpointHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier,
                                                                     ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsEndpointProperties, WebEndpointProperties webEndpointProperties,
                                                                     Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsEndpointProperties.toCorsConfiguration(), new EndpointLinksResolver(
                allEndpoints, basePath), shouldRegisterLinksMapping, null);
    }

    /**
     * shouldRegisterLinksMapping
     *
     * @param webEndpointProperties
     * @param environment
     * @param basePath
     * @return
     */
    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }

    /**
     * Description:  過濾器
     *
     * @param registry
     * @author: GuoTong
     * @date: 2023-06-03 12:32:39
     * @return:void
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new MicrometerTPSInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/doc.html")
                .excludePathPatterns("/swagger-resources/**")
                .excludePathPatterns("/webjars/**")
                .excludePathPatterns("/v2/**")
                .excludePathPatterns("/favicon.ico")
                .excludePathPatterns("/sso/**")
                .excludePathPatterns("/swagger-ui.html/**");
    }


    /**
     * Description:  Bean 如下來監控 JVM 效能指標資訊:
     * http://localhost:8889/actuator/prometheus 指標地址
     *
     * @param applicationName
     * @author: GuoTong
     * @date: 2023-06-03 12:34:36
     * @return:org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer<io.micrometer.core.instrument.MeterRegistry>
     */
    @Bean
    MeterRegistryCustomizer<MeterRegistry> configurer(@Value("${spring.application.name}") String applicationName) {

        return registry -> registry.config().commonTags("application", applicationName);
    }

啟動存取監控

-actuator的看板:http://localhost:port/actuator

-prometheus的看板:http://localhost:port/actuator/prometheus

設定Prometheus的對於本Springboot微服務站點的監控

新增設定 以下內容為SpringBoot應用設定

# Prometheus  啟動完成之後 http://localhost:9090/targets
# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['127.0.0.1:9090']
  ###以下內容為SpringBoot應用設定
  - job_name: 'BackStageApp'
    scrape_interval: 5s
    metrics_path: '/actuator/prometheus'
    static_configs:
      - targets: ['127.0.0.1:8889']
        labels:
          instance: "BackStageApp-prometheus"
          service: "BackStageApp-8889-prometheus"

點選這個執行:prometheus的應用

啟動成功如下

存取prometheus的應用:http://localhost:9090/

可以點選連結跳轉

顯示的是:http://sky-20200720fyp:8889/actuator/prometheus
說明Prometheus設定完成

然後啟動Grafana

啟動成功如下:初始化--啟動有點久,耐性一點

開啟Grafana看板:http://localhost:3000/login

首次登入使用 admin:admin 然後可以設定自己的賬號密碼,也可以跳過Skip

第一次進入如下

設定Prometheus的資料來源

第一步選這個管理設定選單

第二步選這個Datasorce

第三步選這個新增新的Datasorce

第四步選這個Prometheus資料來源

第五步設定Prometheus資料來源的地址和名稱,然後儲存

第六步設定Prometheus的看板

匯入對應的監控 JVM 的 Dashboard 模板,模板編號為 4701。,點選load


填寫這些必填項;匯入自動載入後其他可以不用管,必須選擇下面的剛剛設定的prometheus資料來源,然後選擇import

第七步監控JVM

上一步點選然後選擇import,會進入這個介面,什麼都沒有

選擇自己專案的站點設定的application和instance就行了,重新整理左上角的時間

很多看板自己研究把

建立檔案組

可以把監控看板移加入分類分組