0


快速搭建SpringBoot3+Prometheus+Grafana

快速搭建SpringBoot3+Prometheus+Grafana

一、搭建SpringBoot项目

1.1 创建SpringBoot项目

image-20241023112543699

1.2 修改pom文件配置

<?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>3.3.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.javagpt</groupId>
    <artifactId>prometheus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>prometheus</name>
    <description>prometheus</description>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <!-- spring boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>jakarta.json</groupId>
            <artifactId>jakarta.json-api</artifactId>
            <version>${jakarta-json.version}</version>
        </dependency>
        <!-- spring validation -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <!-- mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
            <scope>runtime</scope>
        </dependency>
        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.23</version>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- mybatis plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>3.5.8</version>
        </dependency>
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
            <version>1.13.6</version>
        </dependency>
    </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>

1.3 创建controller+service+mapper三层文件

image-20241023112650341

1.3.1 controller
ArticleServiceImpl.java
importio.micrometer.core.annotation.Counted;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;/**
 * @BelongsProject: prometheus
 * @BelongsPackage: com.javagpt.prometheus.controller
 * @Author: JavaGPT
 * @CreateTime: 2024-10-23  00:01
 * @Description:
 * @Version: 1.0
 */@RestController@RequestMapping("/article")publicclass c {@Counted(value ="article.get", extraTags ="get", description ="test")@GetMappingpublicStringindex(){return"Hello World";}}
1.3.2 service
ArticleService.java
importcom.javagpt.prometheus.entity.ArticleEntity;importcom.baomidou.mybatisplus.extension.service.IService;/**
* @author 26314
* @description 针对表【tb_article】的数据库操作Service
* @createDate 2024-10-22 23:59:42
*/publicinterfaceArticleServiceextendsIService<ArticleEntity>{}
ArticleServiceImpl.java
importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importcom.javagpt.prometheus.entity.ArticleEntity;importcom.javagpt.prometheus.service.ArticleService;importcom.javagpt.prometheus.mapper.ArticleMapper;importorg.springframework.stereotype.Service;/**
* @author 26314
* @description 针对表【tb_article】的数据库操作Service实现
* @createDate 2024-10-22 23:59:42
*/@ServicepublicclassArticleServiceImplextendsServiceImpl<ArticleMapper,ArticleEntity>implementsArticleService{}
1.3.3 mapper
ArticleMapper.java
importcom.javagpt.prometheus.entity.ArticleEntity;importcom.baomidou.mybatisplus.core.mapper.BaseMapper;importorg.apache.ibatis.annotations.Mapper;/**
* @author 26314
* @description 针对表【tb_article】的数据库操作Mapper
* @createDate 2024-10-22 23:59:42
* @Entity com.javagpt.prometheus.entity.ArticleEntity
*/@MapperpublicinterfaceArticleMapperextendsBaseMapper<ArticleEntity>{}
1.3.4 mapper.xml
ArticleMapper.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.javagpt.prometheus.mapper.ArticleMapper"><resultMapid="BaseResultMap"type="com.javagpt.prometheus.entity.ArticleEntity"><idproperty="id"column="id"jdbcType="INTEGER"/><resultproperty="webId"column="web_id"jdbcType="VARCHAR"/><resultproperty="articleId"column="article_id"jdbcType="VARCHAR"/><resultproperty="author"column="author"jdbcType="VARCHAR"/><resultproperty="title"column="title"jdbcType="VARCHAR"/><resultproperty="abstractContent"column="abstract_content"jdbcType="VARCHAR"/><resultproperty="content"column="content"jdbcType="VARCHAR"/><resultproperty="tag"column="tag"jdbcType="VARCHAR"/><resultproperty="url"column="url"jdbcType="VARCHAR"/><resultproperty="publishTime"column="publish_time"jdbcType="TIMESTAMP"/><resultproperty="commentCount"column="comment_count"jdbcType="INTEGER"/><resultproperty="likeCount"column="like_count"jdbcType="INTEGER"/><resultproperty="readCount"column="read_count"jdbcType="INTEGER"/><resultproperty="createTime"column="create_time"jdbcType="TIMESTAMP"/><resultproperty="creator"column="creator"jdbcType="VARCHAR"/><resultproperty="updateTime"column="update_time"jdbcType="TIMESTAMP"/><resultproperty="updater"column="updater"jdbcType="VARCHAR"/><resultproperty="remark"column="remark"jdbcType="VARCHAR"/></resultMap><sqlid="Base_Column_List">
        id,web_id,article_id,
        author,title,abstract_content,
        content,tag,url,
        publish_time,comment_count,like_count,
        read_count,create_time,creator,
        update_time,updater,remark
    </sql></mapper>

1.4 修改application.yml 文件

spring:application:name: prometheus

  # mysql??datasource:type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://106.55.xx.xx:3306/blog?serverTimezone=Asia/Shanghai&allowMultiQueries=true&rewriteBatchedStatements=trueusername: root
    password: root

management:endpoints:enabled-by-default:true#暴露所有端点信息web:exposure:include:'*'#以web方式暴露server:servlet:context-path: /prometheus
  port:8080# mybatisPlus配置mybatis-plus:# mapper映射地址mapper-locations: classpath:mapper/*.xml# 实体类扫描包路径type-aliases-package: com.javagpt.prometheus.entity
  configuration:# sql打印log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # 开启驼峰命名map-underscore-to-camel-case:trueglobal-config:db-config:# 数据库表前缀table-prefix: t_

1.5 一键启动

Connected to the target VM, address: '127.0.0.1:5815', transport: 'socket'

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.4)

2024-10-23T08:52:37.974+08:00  INFO 33412 --- [prometheus] [           main] c.j.prometheus.PrometheusApplication     : Starting PrometheusApplication using Java 17.0.8 with PID 33412 (D:\develop\java_develop\springboot\prometheus\target\classes started by 26314 in D:\develop\java_develop\springboot\prometheus)
2024-10-23T08:52:37.976+08:00  INFO 33412 --- [prometheus] [           main] c.j.prometheus.PrometheusApplication     : No active profile set, falling back to 1 default profile: "default"
2024-10-23T08:52:38.809+08:00  INFO 33412 --- [prometheus] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2024-10-23T08:52:38.817+08:00  INFO 33412 --- [prometheus] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2024-10-23T08:52:38.818+08:00  INFO 33412 --- [prometheus] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.30]
2024-10-23T08:52:38.855+08:00  INFO 33412 --- [prometheus] [           main] o.a.c.c.C.[.[localhost].[/prometheus]    : Initializing Spring embedded WebApplicationContext
2024-10-23T08:52:38.855+08:00  INFO 33412 --- [prometheus] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 831 ms
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Get /192.168.216.1 network interface 
Get network interface info: name:eth9 (VMware Virtual Ethernet Adapter for VMnet8)
Initialization Sequence datacenterId:0 workerId:5
 _ _   |_  _ _|_. ___ _ |    _ 
| | |\/|_)(_| | |_\  |_)||_|_\ 
     /               |         
                        3.5.8 
2024-10-23T08:52:39.626+08:00  INFO 33412 --- [prometheus] [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 16 endpoints beneath base path '/actuator'
2024-10-23T08:52:39.681+08:00  INFO 33412 --- [prometheus] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/prometheus'
2024-10-23T08:52:39.690+08:00  INFO 33412 --- [prometheus] [           main] c.j.prometheus.PrometheusApplication     : Started PrometheusApplication in 2.003 seconds (process running for 2.618)
2024-10-23T08:52:39.869+08:00  INFO 33412 --- [prometheus] [nio-8080-exec-1] o.a.c.c.C.[.[localhost].[/prometheus]    : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-10-23T08:52:39.869+08:00  INFO 33412 --- [prometheus] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2024-10-23T08:52:39.869+08:00  INFO 33412 --- [prometheus] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 0 ms
2024-10-23T08:52:40.332+08:00  INFO 33412 --- [prometheus] [)-192.168.82.82] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited

1.6 查看默认指标信息

本地访问 http://localhost:8080/prometheus/actuator/prometheus

image-20241023112224311

二、搭建Prometheus

到官网下载最新版 https://prometheus.io/download/

image-20241023122219263

修改

Prometheus.yml

文件

# my global configglobal: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 configurationalerting: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:'/prometheus/actuator/prometheus'#指定抓取的路径static_configs:-targets:['127.0.0.1:8080']labels:nodename:'app-demo'# metrics_path defaults to '/metrics'# scheme defaults to 'http'.# - targets: ["localhost:9090"]

CMD 进入命令行启动

prometheus.exe

image-20241023122348405

三、安装Grafana

3.1 下载

去官网下载最新版Garafana https://grafana.org.cn/grafana/download?platform=windows

image-20241023122637575

3.2 安装

解压之后进入CMD命令行启动

grafana-server.exe

3.3 配置数据源

进入http://localhost:3000 登录,初始账号和密码都是admin,然后找到Data Source,进行如下操作,填好之后点击确认。

image-20241023122855314

3.4 配置SpringBoot程序仪表盘模板

先进入Grafana官网寻找合适的SpringBoot程序模板 https://grafana.com/grafana/dashboards/?search=springboot ,然后将模板ID复制下来。

image-20241023123226041

image-20241023123140615

image-20241023123307746

image-20241023123327341

至此,整个SpringBoot3+Prometheus+Grafana就已经完成搭建啦。

让我们来看看最终的效果图吧。

image-20241023123429133

写在最后

编程精选网(www.codehuber.com),程序员的终身学习网站已上线!

如果这篇【文章】有帮助到你,希望可以给【JavaGPT】点个赞👍,创作不易,如果有对【后端技术】、【前端领域】感兴趣的小可爱,也欢迎关注❤️❤️❤️ 【JavaGPT】❤️❤️❤️,我将会给你带来巨大的【收获与惊喜】💝💝💝!


本文转载自: https://blog.csdn.net/weixin_46294086/article/details/143181066
版权归原作者 JavaGPT 所有, 如有侵权,请联系我们删除。

“快速搭建SpringBoot3+Prometheus+Grafana”的评论:

还没有评论