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

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/prometheusstatic_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: 1sscrape_configs:- job_name: 'example_job'scrape_interval: 1sscrape_timeout: 5sstatic_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: 10086tomcat:mbeanregistry:enabled: truemax-connections: 150threads:max: 50min-spare: 15# spring配置
spring:elasticsearch:uris: http://localhost:9200application:name: "grafana-prometheus-springboot"datasource:url: jdbc:mysql://localhost:3306/goods_system?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghaiusername: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driverhikari: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: trueauto-mapping-behavior: fulllog-impl: org.apache.ibatis.logging.stdout.StdOutImpldefault-statement-timeout: 1mapper-locations: classpath*:mapper/**/*Mapper.xmlglobal-config:db-config:logic-not-delete-value: 1logic-delete-value: 0# prometheus相关监控配置
management:metrics:export:prometheus:enabled: truestep: 1mdescriptions: trueweb:server:auto-time-requests: trueendpoints:prometheus:id: springmetricsweb:exposure:  # 开放哪些指标端点include: health,info,env,prometheus,metrics,httptrace,threaddump,heapdump,springmetrics,hikaricp,*endpoint:metrics:enabled: true

结构图

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

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

配置

server:port: 10086tomcat:mbeanregistry:enabled: truemax-connections: 150threads:max: 50min-spare: 15
# prometheus相关监控配置
management:metrics:export:prometheus:enabled: truestep: 1mdescriptions: trueweb:server:auto-time-requests: trueendpoints:prometheus:id: springmetricsweb: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 {@AutowiredServletWebServerApplicationContext applicationContext;@Autowiredprivate PrometheusMeterRegistry prometheusMeterRegistry;@Beanpublic 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;}@PostConstructpublic void initialize(){log.info("开始执行initialize方法");log.info("initialize执行成功");}@PreDestroypublic 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 {@AutowiredServletWebServerApplicationContext applicationContext;@Autowiredprivate 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 {@AutowiredServletWebServerApplicationContext applicationContext;@Autowiredprivate IUserService userService;@Autowiredprivate PrometheusUtil prometheusUtil;@RequestMapping("/test")public Object get() throws InterruptedException {prometheusUtil.pullGateWay();Thread.sleep(1500);return userService.getById(10);}
}

利用jmeter进行访问

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

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

看板看到的结果就是

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


备注

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

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【IBMMQ】搭建测试队列

一、安装IBMMQ 网上有教程&#xff0c;可以学习 我用的IBMMQ7.5&#xff0c;安装教程 二、创建测试队列 进入工作台&#xff1a; 右击队列管理器&#xff0c;新建队列管理器 写队列管理器名称 点击下一步 点击下一步 点击下一步 端口默认为1414&#xff0c;建议换一个 注…

多线程快速入门

线程与进程区别 每个正在系统上运行的程序都是一个进程。每个进程包含一到多个线程。线程是一组指令的集合&#xff0c;或者是程序的特殊段&#xff0c;它可以在程序里独立执行。也可以把它理解为代码运行的上下文。所以线程基本上是轻量级的进程&#xff0c;它负责在单个程序里…

Linux之查看so/bin依赖(三十一)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 人生格言&#xff1a; 人生…

【Redis】3、Redis主从复制、哨兵、集群

Redis主从复制 主从复制&#xff0c;是指将一台Redis服务器的数据&#xff0c;复制到其他的Redis服务器。前者称为主节点(Master)&#xff0c;后者称为从节点(Slave)&#xff1b;数据的复制是单向的&#xff0c;只能由主节点到从节点。 默认情况下&#xff0c;每台Redis服务器…

linux————ansible

一、认识自动化运维 自动化运维: 将日常IT运维中大量的重复性工作&#xff0c;小到简单的日常检查、配置变更和软件安装&#xff0c;大到整个变更流程的组织调度&#xff0c;由过去的手工执行转为自动化操作&#xff0c;从而减少乃至消除运维中的延迟&#xff0c;实现“零延时”…

时序预测 | MATLAB实现ELM极限学习机时间序列预测未来

时序预测 | MATLAB实现ELM极限学习机时间序列预测未来 目录 时序预测 | MATLAB实现ELM极限学习机时间序列预测未来预测效果基本介绍程序设计参考资料 预测效果 基本介绍 1.MATLAB实现ELM极限学习机时间序列预测未来&#xff1b; 2.运行环境Matlab2018及以上&#xff0c;data为数…

【Redis专题】RedisCluster集群运维与核心原理剖析

目录 课程内容一、Redis集群架构模型二、Redis集群架构搭建&#xff08;单机搭建&#xff09;2.1 在服务器下新建各个节点的配置存放目录2.2 修改配置&#xff08;以redis-8001.conf为例&#xff09; 三、Java代码实战四、Redis集群原理分析4.1 槽位定位算法4.2 跳转重定位4.3 …

Ansible数组同步至Shell脚本数组中

1、ansible中定义数组&#xff0c;我以 ccaPojectList 数组为例子,如下图数组内容 2、需要写一个j2模板的Shell脚本&#xff0c;在j2模板的Shell脚本中引用ansible的 ccaPojectList 数组&#xff0c;大致如下图&#xff1a; {% for item in ccaPojectList %} "{{ item }…

探索程序员需要掌握的算法?

文章目录 一&#xff1a;引言二&#xff1a;常见算法介绍三&#xff1a;重点算法总结 &#x1f389;欢迎来到数据结构学习专栏~探索程序员需要掌握的算法&#xff1f; ☆* o(≧▽≦)o *☆嗨~我是IT陈寒&#x1f379;✨博客主页&#xff1a;IT陈寒的博客&#x1f388;该系列文章…

【漏洞库】Fastjson_1.2.47_rce

文章目录 漏洞描述漏洞编号漏洞评级影响版本漏洞复现- 利用工具- 漏洞环境- 漏洞扫描- 漏洞验证- 深度利用- GetShell- EXP 编写 漏洞挖掘- 寻找入口点- 指纹信息 修复建议- 漏洞修复 漏洞原理 漏洞描述 Fastjson是阿里巴巴公司开源的一款json解析器&#xff0c;其性能优越&am…

TCP服务器使用多路复用

启用复用的作用&#xff1f; 解决linux系统中的io阻塞问题&#xff0c;让多个阻塞io接口可以一起执行。无需开启线程&#xff0c;节省系统资源。 linux系统中的阻塞io有哪些&#xff1f; scanf、read管道、eadTcp套接字、acppet接收连接请求 有以下两种方式实现多路复用&am…

单位固定资产应该怎么管理

对于单位固定资产的管理&#xff0c;更是需要我们以创新的方式&#xff0c;以科技的手段&#xff0c;以严谨的态度来对待。那么&#xff0c;单位固定资产应该如何进行有效的管理呢&#xff1f; 建立一个完善的资产管理系统  我们需要建立一个完善的资产管理系统。这个系统应…

JS如何判断一个变量是否为数组类型?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ 使用 Array.isArray() 方法⭐ 使用 instanceof 操作符⭐ 使用 Object.prototype.toString.call() 方法⭐ 使用 Array.from() 方法⭐ 使用 Array.prototype.isArray 属性&#xff08;不推荐&#xff09;⭐ 写在最后 ⭐ 专栏简介 前端入门之…

使用rpm重新安装包

#查询 rpm -qa | grep cloudstack #卸载 rpm -e cloudstack-agent-4.18.0.0-1.x86_64 #安装 rpm -ivh cloudstack-agent-4.18.0.0-1.x86_64.rpm

Mysql同步数据到Doris的踩坑过程

问题背景 由于项目需要&#xff0c;需要把多个Mysql数据库的数据同步到Doris数据库&#xff0c;然后利用Doris强调的计算和查询能力&#xff0c;来满足业务需求。有关Doris可以查看它的官方文档来了解它。 seatunnel的使用到放弃 缘起 从《第十届GIAC全球互联网架构大会》了…

《Chain-of-Thought Prompting Elicits Reasoning in Large Language Models》全文翻译

《Chain-of-Thought Prompting Elicits Reasoning in Large Language Models》- Chain-of-Thought Prompting Elicits Reasoning in Large Language Models 论文信息摘要1. 介绍2. 思维链提示3. 算术推理3.1 实验设置3.2 结果3.3 消融研究3.4 思想链的稳健性 4. 常识推理5. 符号…

win11本地连接没了怎么办

很多用户在使用win11系统时发现自己的网络连接没有了&#xff0c;遇到这种情况的话&#xff0c;我们应该怎么处理呢&#xff1f;我们可以尝试打开网络图标&#xff0c;下面就是小编整理出的教程&#xff0c;大家一起看看吧。 win11本地连接没了怎么办 方法一&#xff1a; 1、…

Python图像融合处理和 ROI 区域绘制基础

文章目录 一、图像融合二、图像 ROI 区域定位三、图像属性3.1 shape3.2 size3.3 dtype四、图像通道分离及合并4.1、split()函数4.2 merge()函数五、图像类型转换一、图像融合 图像融合通常是指多张图像的信息进行融合,从而获得信息更丰富的结果,能够帮助人们观察或计算机处理…

【echarts】如何将iconfont转换成echart所需的path路径 echarts折线图、柱状图如何设置自定义svg图标

步骤 下载iconfont图标到本地&#xff0c;用浏览器打开&#xff0c;右键查看源代码&#xff0c;或者用开发IDE软件打开&#xff0c;找到path d...&#xff0c;这个就是我们要传递给echart的icon的值。 代码示例&#xff1a; legend: {data: data?.map((item) > item.comp…

Java计算机毕业设计基于SpringBoot音乐网项目(附源码讲解)

目录 用户端 第一步&#xff1a;用户注册 第二步&#xff1a;用户登录 第三步&#xff1a;平台首页&#xff08;可查看平台歌单、歌手详细信息操作等等&#xff09; 第四步&#xff1a;查看歌单 第五步&#xff1a;歌单详情操作&#xff08;歌单评价、歌单歌曲下载、歌单…