SpringBoot + Prometheus + Grafana 打造可视化监控

news2024/12/25 23:47:52

SpringBoot + Prometheus + Grafana 打造可视化监控

文章目录

  • SpringBoot + Prometheus + Grafana 打造可视化监控
    • 常见的监控组件搭配
    • 安装Prometheus
    • 安装Grafana
    • 搭建SpringBoot项目
      • 引入依赖
      • 示例:监控SpringBoot内置Tomcat线程池的情况
      • grafana创建监控看板
    • 后台SpringBoot服务添加自定义监控数据,上送给prometheus

常见的监控组件搭配

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

安装Prometheus

  • 本次使用的是windows版本进行学习测试
  • prometheus-2.46.0.windows-amd64

下载地址

  • prometheus.io/download/

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

解压后修改prometheus.yml文件,配置数据采集的目标信息

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

# 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:
  # 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'.
    # 暴露路径
    metrics_path: /actuator/prometheus
    
    static_configs:
      # SpringBoot的ip和端口
      - targets: ["localhost:10086"]

启动prometheus

prometheus.exe

prometheus.exe–config.file=prometheus.yml

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

访问promethus

http://localhost:9090/

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

要修改Prometheus的拉取数据时间为1秒,您需要调整Prometheus的配置文件中的以下两个参数:

  1. scrape_interval:这个参数指定了Prometheus拉取目标配置的时间间隔,单位为秒。您可以将该参数设置为1秒,以实现每秒拉取一次数据。
  2. scrape_timeout:这个参数指定了Prometheus拉取目标配置的超时时间,单位为秒。您需要将该参数设置为大于1秒的值,以确保Prometheus有足够的时间完成对目标配置的拉取。

以下是一个示例Prometheus配置文件(通常命名为prometheus.yml),其中将scrape_interval设置为1秒:

global:
  scrape_interval: 1s

scrape_configs:
  - job_name: 'example_job'
    scrape_interval: 1s
    scrape_timeout: 5s
    static_configs:
      - targets: ['example.com:8080']

在上述示例中,scrape_interval被设置为1秒,而scrape_timeout被设置为5秒。请根据您的实际需求进行调整。

请注意,将拉取时间间隔设置为非常短的时间可能会导致Prometheus对目标配置产生大量的请求,从而可能对目标应用程序造成负面影响。因此,在实际应用中,请根据目标应用程序的性能和可接受的网络负载进行适当的调整。

安装Grafana

下载地址

https://mirrors.huaweicloud.com/grafana/

  • grafana-enterprise-8.4.1.windows-amd64

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

解压后如图

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

启动grafana

双击:grafana-server.exe

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

访问grafana

默认账号:admin
默认密码:admin

登录地址

http://127.0.0.1:3000/login

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

搭建SpringBoot项目

引入依赖

 <!--grafana+prometheus必须依赖  开始-->
        <!--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>
        </dependency>
        <!--主动上送metric-->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_pushgateway</artifactId>
        </dependency>
        <!--grafana+prometheus必须依赖  结束-->

全部

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.kang</groupId>
    <artifactId>grafana-prometheus-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>grafana-prometheus-springboot</name>
    <description>grafana-prometheus-springboot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>HdrHistogram</artifactId>
                    <groupId>org.hdrhistogram</groupId>
                </exclusion>
            </exclusions>
        </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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.3.5.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.4.0</version>
        </dependency>

        <!-- mybatis plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>
        <!--代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <!-- mybatis plus 代码生成器 -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!--grafana+prometheus必须依赖  开始-->
        <!--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>
        </dependency>
        <!--主动上送metric-->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_pushgateway</artifactId>
        </dependency>
        <!--grafana+prometheus必须依赖  结束-->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

yaml配置

server:
  port: 10086
  tomcat:
    mbeanregistry:
      enabled: true
    max-connections: 150
    threads:
      max: 50
      min-spare: 15


# spring配置
spring:
  elasticsearch:
    uris: http://localhost:9200
  application:
    name: "grafana-prometheus-springboot"
  datasource:
    url: jdbc:mysql://localhost:3306/goods_system?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      connection-timeout: 1000          # 获取连接超时时间
      maximum-pool-size: 50             # 连接池中允许的最大连接数
      minimum-idle: 5                   # 连接池中保持的最小空闲连接数
      idle-timeout: 30000               # 连接在池中保持空闲的最大时间,超过该时间将被释放
      pool-name: grafana-hikari-pool    # 连接池的名称

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    default-statement-timeout: 1
  mapper-locations: classpath*:mapper/**/*Mapper.xml
  global-config:
    db-config:
      logic-not-delete-value: 1
      logic-delete-value: 0


# prometheus相关监控配置
management:
  metrics:
    export:
      prometheus:
        enabled: true
        step: 1m
        descriptions: true
  web:
    server:
      auto-time-requests: true
  endpoints:
    prometheus:
      id: springmetrics
    web:
      exposure:  # 开放哪些指标端点
        include: health,info,env,prometheus,metrics,httptrace,threaddump,heapdump,springmetrics,hikaricp,*
  endpoint:
    metrics:
      enabled: true

结构图

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

示例:监控SpringBoot内置Tomcat线程池的情况

配置

server:
  port: 10086
  tomcat:
    mbeanregistry:
      enabled: true
    max-connections: 150
    threads:
      max: 50
      min-spare: 15
# prometheus相关监控配置
management:
  metrics:
    export:
      prometheus:
        enabled: true
        step: 1m
        descriptions: true
  web:
    server:
      auto-time-requests: true
  endpoints:
    prometheus:
      id: springmetrics
    web:
      exposure:  # 开放哪些指标端点
        include: health,info,env,prometheus,metrics,httptrace,threaddump,heapdump,springmetrics,hikaricp,*
  endpoint:
    metrics:
      enabled: true

访问/actuator/prometheus

http://localhost:10086/actuator/prometheus

# HELP tomcat_global_sent_bytes_total  
# TYPE tomcat_global_sent_bytes_total counter
tomcat_global_sent_bytes_total{name="http-nio-10086",} 653223.0
# HELP hikaricp_connections_idle Idle connections
# TYPE hikaricp_connections_idle gauge
hikaricp_connections_idle{pool="grafana-hikari-pool",} 47.0
# HELP tomcat_global_error_total  
# TYPE tomcat_global_error_total counter
tomcat_global_error_total{name="http-nio-10086",} 0.0
# HELP tomcat_servlet_request_seconds  
# TYPE tomcat_servlet_request_seconds summary
tomcat_servlet_request_seconds_count{name="dispatcherServlet",} 2029.0
tomcat_servlet_request_seconds_sum{name="dispatcherServlet",} 77.433
# HELP system_cpu_count The number of processors available to the Java virtual machine
# TYPE system_cpu_count gauge
system_cpu_count 12.0
# HELP jvm_threads_live_threads The current number of live threads including both daemon and non-daemon threads
# TYPE jvm_threads_live_threads gauge
jvm_threads_live_threads 124.0
# HELP hikaricp_connections_timeout_total Connection timeout total count
# TYPE hikaricp_connections_timeout_total counter
hikaricp_connections_timeout_total{pool="grafana-hikari-pool",} 0.0
# HELP tomcat_threads_config_max_threads  
# TYPE tomcat_threads_config_max_threads gauge
tomcat_threads_config_max_threads{name="http-nio-10086",} 50.0
# HELP process_cpu_usage The "recent cpu usage" for the Java Virtual Machine process
# TYPE process_cpu_usage gauge
process_cpu_usage 8.347234082417593E-4
# HELP hikaricp_connections_max Max connections
# TYPE hikaricp_connections_max gauge
hikaricp_connections_max{pool="grafana-hikari-pool",} 50.0
# HELP jvm_classes_loaded_classes The number of classes that are currently loaded in the Java virtual machine
# TYPE jvm_classes_loaded_classes gauge
jvm_classes_loaded_classes 10820.0
# HELP tomcat_sessions_active_max_sessions  
# TYPE tomcat_sessions_active_max_sessions gauge
tomcat_sessions_active_max_sessions 0.0
# HELP jdbc_connections_min Minimum number of idle connections in the pool.
# TYPE jdbc_connections_min gauge
jdbc_connections_min{name="dataSource",} 5.0
# HELP hikaricp_connections_pending Pending threads
# TYPE hikaricp_connections_pending gauge
hikaricp_connections_pending{pool="grafana-hikari-pool",} 0.0
# HELP tomcat_sessions_rejected_sessions_total  
# TYPE tomcat_sessions_rejected_sessions_total counter
tomcat_sessions_rejected_sessions_total 0.0
# HELP tomcat_global_request_seconds  
# TYPE tomcat_global_request_seconds summary
tomcat_global_request_seconds_count{name="http-nio-10086",} 2028.0
tomcat_global_request_seconds_sum{name="http-nio-10086",} 80.738
# HELP jvm_gc_max_data_size_bytes Max size of old generation memory pool
# TYPE jvm_gc_max_data_size_bytes gauge
jvm_gc_max_data_size_bytes 2.751463424E9
# HELP jvm_gc_pause_seconds Time spent in GC pause
# TYPE jvm_gc_pause_seconds summary
jvm_gc_pause_seconds_count{action="end of major GC",cause="Metadata GC Threshold",} 1.0
jvm_gc_pause_seconds_sum{action="end of major GC",cause="Metadata GC Threshold",} 0.033
jvm_gc_pause_seconds_count{action="end of minor GC",cause="Metadata GC Threshold",} 1.0
jvm_gc_pause_seconds_sum{action="end of minor GC",cause="Metadata GC Threshold",} 0.005
jvm_gc_pause_seconds_count{action="end of minor GC",cause="Allocation Failure",} 3.0
jvm_gc_pause_seconds_sum{action="end of minor GC",cause="Allocation Failure",} 0.037
# HELP jvm_gc_pause_seconds_max Time spent in GC pause
# TYPE jvm_gc_pause_seconds_max gauge
jvm_gc_pause_seconds_max{action="end of major GC",cause="Metadata GC Threshold",} 0.0
jvm_gc_pause_seconds_max{action="end of minor GC",cause="Metadata GC Threshold",} 0.0
jvm_gc_pause_seconds_max{action="end of minor GC",cause="Allocation Failure",} 0.02
# HELP tomcat_sessions_active_current_sessions  
# TYPE tomcat_sessions_active_current_sessions gauge
tomcat_sessions_active_current_sessions 0.0
# HELP tomcat_sessions_alive_max_seconds  
# TYPE tomcat_sessions_alive_max_seconds gauge
tomcat_sessions_alive_max_seconds 0.0
# HELP hikaricp_connections_min Min connections
# TYPE hikaricp_connections_min gauge
hikaricp_connections_min{pool="grafana-hikari-pool",} 5.0
# HELP tomcat_threads_current_threads  
# TYPE tomcat_threads_current_threads gauge
tomcat_threads_current_threads{name="http-nio-10086",} 50.0
# HELP jvm_memory_max_bytes The maximum amount of memory in bytes that can be used for memory management
# TYPE jvm_memory_max_bytes gauge
jvm_memory_max_bytes{area="heap",id="PS Survivor Space",} 1.6252928E7
jvm_memory_max_bytes{area="heap",id="PS Old Gen",} 2.751463424E9
jvm_memory_max_bytes{area="heap",id="PS Eden Space",} 1.336410112E9
jvm_memory_max_bytes{area="nonheap",id="Metaspace",} -1.0
jvm_memory_max_bytes{area="nonheap",id="Code Cache",} 2.5165824E8
jvm_memory_max_bytes{area="nonheap",id="Compressed Class Space",} 1.073741824E9
# HELP tomcat_servlet_error_total  
# TYPE tomcat_servlet_error_total counter
tomcat_servlet_error_total{name="dispatcherServlet",} 0.0
# HELP jvm_threads_daemon_threads The current number of live daemon threads
# TYPE jvm_threads_daemon_threads gauge
jvm_threads_daemon_threads 107.0
# HELP jvm_memory_used_bytes The amount of used memory
# TYPE jvm_memory_used_bytes gauge
jvm_memory_used_bytes{area="heap",id="PS Survivor Space",} 1.6238736E7
jvm_memory_used_bytes{area="heap",id="PS Old Gen",} 2.7538488E7
jvm_memory_used_bytes{area="heap",id="PS Eden Space",} 2.36629096E8
jvm_memory_used_bytes{area="nonheap",id="Metaspace",} 5.5265272E7
jvm_memory_used_bytes{area="nonheap",id="Code Cache",} 1.5770176E7
jvm_memory_used_bytes{area="nonheap",id="Compressed Class Space",} 7257680.0
# HELP tomcat_thread_pool_info tomcat_thread_pool_info
# TYPE tomcat_thread_pool_info gauge
# HELP tomcat_global_request_max_seconds  
# TYPE tomcat_global_request_max_seconds gauge
tomcat_global_request_max_seconds{name="http-nio-10086",} 1.325
# HELP process_uptime_seconds The uptime of the Java virtual machine
# TYPE process_uptime_seconds gauge
process_uptime_seconds 414.56
# HELP system_cpu_usage The "recent cpu usage" for the whole system
# TYPE system_cpu_usage gauge
system_cpu_usage 0.15617296080373955
# HELP tomcat_sessions_expired_sessions_total  
# TYPE tomcat_sessions_expired_sessions_total counter
tomcat_sessions_expired_sessions_total 0.0
# HELP tomcat_servlet_request_max_seconds  
# TYPE tomcat_servlet_request_max_seconds gauge
tomcat_servlet_request_max_seconds{name="dispatcherServlet",} 1.292
# HELP jvm_buffer_count_buffers An estimate of the number of buffers in the pool
# TYPE jvm_buffer_count_buffers gauge
jvm_buffer_count_buffers{id="direct",} 53.0
jvm_buffer_count_buffers{id="mapped",} 0.0
# HELP jvm_threads_states_threads The current number of threads having NEW state
# TYPE jvm_threads_states_threads gauge
jvm_threads_states_threads{state="runnable",} 21.0
jvm_threads_states_threads{state="blocked",} 0.0
jvm_threads_states_threads{state="waiting",} 49.0
jvm_threads_states_threads{state="timed-waiting",} 54.0
jvm_threads_states_threads{state="new",} 0.0
jvm_threads_states_threads{state="terminated",} 0.0
# HELP tomcat_cache_access_total  
# TYPE tomcat_cache_access_total counter
tomcat_cache_access_total 0.0
# HELP jvm_buffer_total_capacity_bytes An estimate of the total capacity of the buffers in this pool
# TYPE jvm_buffer_total_capacity_bytes gauge
jvm_buffer_total_capacity_bytes{id="direct",} 421904.0
jvm_buffer_total_capacity_bytes{id="mapped",} 0.0
# HELP jvm_gc_live_data_size_bytes Size of old generation memory pool after a full GC
# TYPE jvm_gc_live_data_size_bytes gauge
jvm_gc_live_data_size_bytes 1.49782E7
# HELP jvm_memory_committed_bytes The amount of memory in bytes that is committed for the Java virtual machine to use
# TYPE jvm_memory_committed_bytes gauge
jvm_memory_committed_bytes{area="heap",id="PS Survivor Space",} 1.6252928E7
jvm_memory_committed_bytes{area="heap",id="PS Old Gen",} 1.27401984E8
jvm_memory_committed_bytes{area="heap",id="PS Eden Space",} 2.69484032E8
jvm_memory_committed_bytes{area="nonheap",id="Metaspace",} 6.0342272E7
jvm_memory_committed_bytes{area="nonheap",id="Code Cache",} 1.5794176E7
jvm_memory_committed_bytes{area="nonheap",id="Compressed Class Space",} 8175616.0
# HELP tomcat_threads_busy_threads  
# TYPE tomcat_threads_busy_threads gauge
tomcat_threads_busy_threads{name="http-nio-10086",} 1.0
# HELP tomcat_cache_hit_total  
# TYPE tomcat_cache_hit_total counter
tomcat_cache_hit_total 0.0
# HELP jvm_gc_memory_allocated_bytes_total Incremented for an increase in the size of the young generation memory pool after one GC to before the next
# TYPE jvm_gc_memory_allocated_bytes_total counter
jvm_gc_memory_allocated_bytes_total 5.43316024E8
# HELP jvm_classes_unloaded_classes_total The total number of classes unloaded since the Java virtual machine has started execution
# TYPE jvm_classes_unloaded_classes_total counter
jvm_classes_unloaded_classes_total 2.0
# HELP hikaricp_connections_usage_seconds Connection usage time
# TYPE hikaricp_connections_usage_seconds summary
hikaricp_connections_usage_seconds_count{pool="grafana-hikari-pool",} 2002.0
hikaricp_connections_usage_seconds_sum{pool="grafana-hikari-pool",} 40.873
# HELP hikaricp_connections_usage_seconds_max Connection usage time
# TYPE hikaricp_connections_usage_seconds_max gauge
hikaricp_connections_usage_seconds_max{pool="grafana-hikari-pool",} 0.306
# HELP http_server_requests_seconds  
# TYPE http_server_requests_seconds summary
http_server_requests_seconds_count{exception="None",method="GET",outcome="SUCCESS",status="200",uri="/actuator/prometheus",} 28.0
http_server_requests_seconds_sum{exception="None",method="GET",outcome="SUCCESS",status="200",uri="/actuator/prometheus",} 4.8066835
http_server_requests_seconds_count{exception="None",method="GET",outcome="SUCCESS",status="200",uri="/user/test",} 2000.0
http_server_requests_seconds_sum{exception="None",method="GET",outcome="SUCCESS",status="200",uri="/user/test",} 74.450206
# HELP http_server_requests_seconds_max  
# TYPE http_server_requests_seconds_max gauge
http_server_requests_seconds_max{exception="None",method="GET",outcome="SUCCESS",status="200",uri="/actuator/prometheus",} 0.1568263
http_server_requests_seconds_max{exception="None",method="GET",outcome="SUCCESS",status="200",uri="/user/test",} 0.5168904
# HELP tomcat_sessions_created_sessions_total  
# TYPE tomcat_sessions_created_sessions_total counter
tomcat_sessions_created_sessions_total 0.0
# HELP hikaricp_connections_acquire_seconds Connection acquire time
# TYPE hikaricp_connections_acquire_seconds summary
hikaricp_connections_acquire_seconds_count{pool="grafana-hikari-pool",} 2002.0
hikaricp_connections_acquire_seconds_sum{pool="grafana-hikari-pool",} 9.510603
# HELP hikaricp_connections_acquire_seconds_max Connection acquire time
# TYPE hikaricp_connections_acquire_seconds_max gauge
hikaricp_connections_acquire_seconds_max{pool="grafana-hikari-pool",} 0.3078482
# HELP jvm_buffer_memory_used_bytes An estimate of the memory that the Java virtual machine is using for this buffer pool
# TYPE jvm_buffer_memory_used_bytes gauge
jvm_buffer_memory_used_bytes{id="direct",} 421904.0
jvm_buffer_memory_used_bytes{id="mapped",} 0.0
# HELP jvm_gc_memory_promoted_bytes_total Count of positive increases in the size of the old generation memory pool before GC to after GC
# TYPE jvm_gc_memory_promoted_bytes_total counter
jvm_gc_memory_promoted_bytes_total 1.8795408E7
# HELP tomcat_global_received_bytes_total  
# TYPE tomcat_global_received_bytes_total counter
tomcat_global_received_bytes_total{name="http-nio-10086",} 0.0
# HELP hikaricp_connections Total connections
# TYPE hikaricp_connections gauge
hikaricp_connections{pool="grafana-hikari-pool",} 47.0
# HELP hikaricp_connections_creation_seconds_max Connection creation time
# TYPE hikaricp_connections_creation_seconds_max gauge
hikaricp_connections_creation_seconds_max{pool="grafana-hikari-pool",} 0.038
# HELP hikaricp_connections_creation_seconds Connection creation time
# TYPE hikaricp_connections_creation_seconds summary
hikaricp_connections_creation_seconds_count{pool="grafana-hikari-pool",} 46.0
hikaricp_connections_creation_seconds_sum{pool="grafana-hikari-pool",} 0.479
# HELP hikaricp_connections_active Active connections
# TYPE hikaricp_connections_active gauge
hikaricp_connections_active{pool="grafana-hikari-pool",} 0.0
# HELP jdbc_connections_max Maximum number of active connections that can be allocated at the same time.
# TYPE jdbc_connections_max gauge
jdbc_connections_max{name="dataSource",} 50.0
# HELP process_start_time_seconds Start time of the process since unix epoch.
# TYPE process_start_time_seconds gauge
process_start_time_seconds 1.693547474058E9
# HELP jvm_threads_peak_threads The peak live thread count since the Java virtual machine started or peak was reset
# TYPE jvm_threads_peak_threads gauge
jvm_threads_peak_threads 125.0
# HELP logback_events_total Number of error level events that made it to the logs
# TYPE logback_events_total counter
logback_events_total{level="warn",} 5.0
logback_events_total{level="debug",} 0.0
logback_events_total{level="error",} 0.0
logback_events_total{level="trace",} 0.0
logback_events_total{level="info",} 16.0

prometheus的管理页面

http://localhost:9090/

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

grafana创建监控看板

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传


数据源创建好之后就可以创建监控看板了dashboard

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

这是自己创建好的一个例子

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

  • 根据自己的场景选择合适的监控图标,能更好的展示我们监控的指标

后台SpringBoot服务添加自定义监控数据,上送给prometheus

依赖

        <!--grafana+prometheus必须依赖  开始-->
        <!--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>
        </dependency>
        <!--主动上送metric-->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_pushgateway</artifactId>
        </dependency>
        <!--grafana+prometheus必须依赖  结束-->

注册监控点

package com.kang.grafana.monitor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.Executor;

/**
 * @Author Emperor Kang
 * @ClassName PrometheusMetricMonitor
 * @Description prometheus监控类
 * @Date 2023/8/31 15:51
 * @Version 1.0
 * @Motto 让营地比你来时更干净
 */
@Slf4j
@Configuration
public class PrometheusMetricMonitor {
    @Autowired
    ServletWebServerApplicationContext applicationContext;

    @Autowired
    private PrometheusMeterRegistry prometheusMeterRegistry;

    @Bean
    public Gauge gauge(){
        Gauge gauge = Gauge.build()
                .name("tomcat_thread_pool_info")
                .labelNames("attributeDescription")
                .help("tomcat_thread_pool_info")
                .register();
        CollectorRegistry prometheusRegistry = prometheusMeterRegistry.getPrometheusRegistry();
        prometheusRegistry.register(gauge);
        return gauge;
    }


    @PostConstruct
    public void initialize(){
        log.info("开始执行initialize方法");
        log.info("initialize执行成功");
    }

    @PreDestroy
    public void preDestroy(){
        log.info("开始执行preDestroy方法");
    }
}

每次调用去上送自己的实时数据

package com.kang.grafana.monitor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.prometheus.client.Gauge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

/**
 * @Author Emperor Kang
 * @ClassName PrometheusUtil
 * @Description TODO
 * @Date 2023/9/4 18:43
 * @Version 1.0
 * @Motto 让营地比你来时更干净
 */
@Component
public class PrometheusUtil {
    @Autowired
    ServletWebServerApplicationContext applicationContext;

    @Autowired
    private Gauge gauge;

    /**
     * 上送数据
     */
    public void pullGateWay() {
        Executor executor = ((TomcatWebServer) applicationContext.getWebServer()).getTomcat().getConnector().getProtocolHandler().getExecutor();
        // 获取内置tomcat的线程池情况
        String executorInfo = JSON.toJSONString(executor, SerializerFeature.WriteMapNullValue);
        JSONObject tomcatThreadPoolInfo = JSON.parseObject(executorInfo);
        gauge.labels("activeCount").set(tomcatThreadPoolInfo.getLong("activeCount"));
        gauge.labels("largestPoolSize").set(tomcatThreadPoolInfo.getLong("largestPoolSize"));
        gauge.labels("poolSize").set(tomcatThreadPoolInfo.getLong("poolSize"));
        gauge.labels("taskCount").set(tomcatThreadPoolInfo.getLong("taskCount"));
        gauge.labels("corePoolSize").set(tomcatThreadPoolInfo.getLong("corePoolSize"));
        gauge.labels("submittedCount").set(tomcatThreadPoolInfo.getLong("submittedCount"));
        gauge.labels("completedTaskCount").set(tomcatThreadPoolInfo.getLong("completedTaskCount"));
        gauge.labels("maximumPoolSize").set(tomcatThreadPoolInfo.getLong("maximumPoolSize"));
        gauge.labels("queue").set(tomcatThreadPoolInfo.getObject("queue", JSONArray.class).size());
        gauge.labels("threadRenewalDelay").set(tomcatThreadPoolInfo.getLong("threadRenewalDelay"));
    }
}

package com.kang.grafana.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.kang.grafana.monitor.PrometheusUtil;
import com.kang.grafana.service.IUserService;
import io.prometheus.client.Gauge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Executor;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zkk
 * @since 2023-01-04
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    ServletWebServerApplicationContext applicationContext;

    @Autowired
    private IUserService userService;

    @Autowired
    private PrometheusUtil prometheusUtil;

    @RequestMapping("/test")
    public Object get() throws InterruptedException {
        prometheusUtil.pullGateWay();
        Thread.sleep(1500);
        return userService.getById(10);
    }
}

利用jmeter进行访问

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

看板看到的结果就是

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传


备注

这里只是初步了解学习,中间估计还有很多为了解到的东西,本次仅限了解使用,待打磨

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1005891.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【深度学习】 Python 和 NumPy 系列教程(十):NumPy详解:2、数组操作(索引和切片、形状操作、转置操作、拼接操作)

目录 一、前言 二、实验环境 三、NumPy 0、多维数组对象&#xff08;ndarray&#xff09; 1. 多维数组的属性 1、创建数组 2、数组操作 1. 索引和切片 a. 索引 b. 切片 2. 形状操作 a. 获取数组形状 b. 改变数组形状 c. 展平数组 3. 转置操作 a. 使用.T属性 b…

Redis模块四:常见的数据类型和使用

目录 Redis 的 5 大基础数据类型 ①字符串类型(String) ②字典类型(Hash) ③列表类型(List) ④集合类型(Set) ⑤有序集合类型(ZSet) Redis 的 5 大基础数据类型 String——字符串类型 Hash——字典类型 List——列表类型 Set——集合类型 ZSet——有序集合类型 …

后发而先至的腾讯混元大模型,到底有哪些技术亮点?

2023年的夏天已经结束了&#xff0c;但是&#xff0c;围绕AIGC大模型的关注热度&#xff0c;却丝毫没有衰退的意思。 在过去的大半年里&#xff0c;我们亲眼见证了大模型浪潮的崛起&#xff0c;甚至可以说是疯狂。截止7月&#xff0c;国内的大模型数量&#xff0c;已经超过130个…

MySQL与ES数据同步之异步调用

文章目录 简述SpringBoot项目引入依赖配置文件项目结构实体类配置类RabbitMQ交换机队列声明&#xff0c;绑定配置类回调接口配置类 Mapper接口UserMapper接口UserEsMapper Controller类Service接口Service实现类监听类/消费者 简述 上一篇是同步调用&#xff0c;我们在中间加上…

【海思SS626 | 开发环境】VMware17安装Ubuntu 18.04.6

目录 一、下载 Ubuntu 18.04.6 LTS二、VMware17创建虚拟机三、安装Ubuntu18.04LTS四、安装其他软件五、总结 一、下载 Ubuntu 18.04.6 LTS 问题&#xff1a;为什么要下载 Ubuntu18.04.6 LTS 而不是使用最新的&#xff0c;或者其他Linux发行版&#xff1f; 答&#xff1a;在ss6…

Python 图形化界面基础篇:使用框架( Frame )组织界面

Python 图形化界面基础篇&#xff1a;使用框架&#xff08; Frame &#xff09;组织界面 引言什么是 Tkinter 框架&#xff08; Frame &#xff09;&#xff1f;步骤1&#xff1a;导入 Tkinter 模块步骤2&#xff1a;创建 Tkinter 窗口步骤3&#xff1a;创建框架&#xff08; F…

如何做到安全上网

随着信息化的发展&#xff0c;企业日常办公越来越依赖互联网&#xff0c;而访问互联网过程中&#xff0c;会遇到各种各样不容忽视的风险&#xff0c;例如员工主动故意的数据泄漏&#xff0c;后台应用程序偷偷向外部发信息&#xff0c;木马间谍软件的外联&#xff0c;以及各种挖…

聚观早报 | 荣耀V Purse定档;哪吒S迎来最新OTA升级

【聚观365】9月13日消息 荣耀V Purse定档 哪吒S迎来最新OTA升级 宝马将向其英国工厂投资7.5亿美元 英伟达称霸AI芯片领域致初创公司融资难 甲骨文第一财季收入约125亿美元增长9% 荣耀V Purse定档 不久前&#xff0c;荣耀官方推出了全新的荣耀Magic V2内折叠屏旗舰&#x…

【Linux从入门到精通】信号(信号保存 信号的处理)

本篇文章接着信号&#xff08;初识信号 & 信号的产生&#xff09;进行讲解。学完信号的产生后&#xff0c;我们也了解了信号的一些结论。同时还留下了很多疑问&#xff1a; 上篇文章所说的所有信号产生&#xff0c;最终都要有OS来进行执行&#xff0c;为什么呢&#xff1f;…

在Android studio 创建Flutter项目运行出现问题总结

在Android studio 中配置Flutter出现的问题 A problem occurred configuring root project ‘android’出现这个问题。解决办法 首先找到flutter配置的位置 在D:\xxx\flutter\packages\flutter_tools\gradle位置中的flutter.gradle buildscript { repositories { googl…

相机坐标系 -> 像素坐标系

代码链接&#xff1a;https://github.com/PanJinquan/python-learning-notes/blob/master/modules/utils_3d/camera_tools.py def __cam2pixel(cam_coord, f, c):"""相机坐标系 -> 像素坐标系: (f / dx) * (X / Z) f * (X / Z) / dxcx,ppx260.166; cy,ppy…

分库分表---理论

目录 一、垂直切分 1、垂直分库 2、垂直分表 3、垂直切分优缺点 二、水平切分 1、水平分库 2、水平分表 3、水平切分优缺点 三、数据分片规则 1、Hash取模分表 2、数值Range分表 3、一致性Hash算法 四、分库分表带来的问题 1、分布式事务问题 2、跨节点关联查询…

【FAQ】本地录像视频文件如何推送到视频监控平台EasyCVR进行AI视频智能分析?

安防监控平台EasyCVR支持多协议、多类型设备接入&#xff0c;可以实现多现场的前端摄像头等设备统一集中接入与视频汇聚管理&#xff0c;并能进行视频高清监控、录像、云存储与磁盘阵列存储、检索与回放、级联共享等视频功能。视频汇聚平台既具备传统安防监控、视频监控的视频能…

Vue2电商前台项目——完成Search搜索模块业务

Vue2电商前台项目——完成Search搜索模块业务 Vue基础知识点击此处——Vue.js 文章目录 Vue2电商前台项目——完成Search搜索模块业务一、项目开发的步骤二、各种请求数据并展示数据1、写Search模块的接口2、写Vuex中的search仓库3、组件拿到search仓库的数据&#xff08;1&…

详解HPE MSA 2040存储初始化配置划分卷

哈喽大家好&#xff0c;欢迎来到虚拟化时代君&#xff08;XNHCYL&#xff09;。 “ 大家好&#xff0c;我是虚拟化时代君&#xff0c;一位潜心于互联网的技术宅男。这里每天为你分享各种你感兴趣的技术、教程、软件、资源、福利……&#xff08;每天更新不间断&#xff0c;福…

mock技术在测试中的应用

技术简介 mock技术又叫测试桩、挡板 在软件测试中&#xff0c;对于一些不容易构造、获取的对象&#xff0c;用一个虚拟的对象来代替它&#xff0c;以达到相同的效果&#xff0c;这个虚拟的对象就是mock。 mock技术并不是只有测试领域用&#xff0c;最早是在开发领域应用&…

互联网电视流氓乱收费被市场惩罚,传统品牌合力挤压互联网电视

市调机构洛图科技&#xff08;RUNTO&#xff09;公布的6月份数据显示&#xff0c;传统电视品牌强势反弹&#xff0c;海信、TCL、创维的销量分别为60万台、58万台、57万台&#xff0c;名次分别为第一名、第三名、第四名&#xff0c;而曾连续数年位居国内电视行业第一名的某互联网…

精品基于NET实现的汽配网上商城系统

《[含文档PPT源码等]精品基于NET实现的汽配网上商城系统》该项目含有源码、文档、PPT、配套开发软件、软件安装教程、项目发布教程等 软件开发环境及开发工具&#xff1a; 开发软件&#xff1a;VS 2017 &#xff08;版本2017以上即可&#xff0c;不能低于2017&#xff09; 数…

第十二章总结

一.集合类概述 java.util包中提供了一些集合类&#xff0c;这些集合类又被称为容器。 集合类与数组的不同之处&#xff1a; 数组的长度是固定的&#xff0c;集合的长度是可变的&#xff1a;数组用来存放基本类型的数据&#xff0c;集合用来存放对象的引用。 常…

windows10系统下Python3.11中安装Numpy库教程

Python3.11中安装Numpy库目录 项目场景&#xff1a;问题描述解决方案&#xff1a;①下载Numpy文件②把NumPy文件放到Python安装的Scripts文件夹里。③安装numpy④安装验证 项目场景&#xff1a; numpy是开源的数值计算扩展&#xff0c;用于数据分析、机器学习、科学计算的重要…