自学内容网 自学内容网

快速搭建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

import io.micrometer.core.annotation.Counted;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.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")
public class c {

    @Counted(value = "article.get", extraTags = "get", description = "test")
    @GetMapping
    public String index() {

        return "Hello World";
    }
}

1.3.2 service

ArticleService.java

import com.javagpt.prometheus.entity.ArticleEntity;
import com.baomidou.mybatisplus.extension.service.IService;

/**
* @author 26314
* @description 针对表【tb_article】的数据库操作Service
* @createDate 2024-10-22 23:59:42
*/
public interface ArticleService extends IService<ArticleEntity> {

}

ArticleServiceImpl.java

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javagpt.prometheus.entity.ArticleEntity;
import com.javagpt.prometheus.service.ArticleService;
import com.javagpt.prometheus.mapper.ArticleMapper;
import org.springframework.stereotype.Service;

/**
* @author 26314
* @description 针对表【tb_article】的数据库操作Service实现
* @createDate 2024-10-22 23:59:42
*/
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticleEntity>
    implements ArticleService{

}
1.3.3 mapper

ArticleMapper.java

import com.javagpt.prometheus.entity.ArticleEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

/**
* @author 26314
* @description 针对表【tb_article】的数据库操作Mapper
* @createDate 2024-10-22 23:59:42
* @Entity com.javagpt.prometheus.entity.ArticleEntity
*/
@Mapper
public interface ArticleMapper extends BaseMapper<ArticleEntity> {

}
1.3.4 mapper.xml

ArticleMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.javagpt.prometheus.mapper.ArticleMapper">

    <resultMap id="BaseResultMap" type="com.javagpt.prometheus.entity.ArticleEntity">
            <id property="id" column="id" jdbcType="INTEGER"/>
            <result property="webId" column="web_id" jdbcType="VARCHAR"/>
            <result property="articleId" column="article_id" jdbcType="VARCHAR"/>
            <result property="author" column="author" jdbcType="VARCHAR"/>
            <result property="title" column="title" jdbcType="VARCHAR"/>
            <result property="abstractContent" column="abstract_content" jdbcType="VARCHAR"/>
            <result property="content" column="content" jdbcType="VARCHAR"/>
            <result property="tag" column="tag" jdbcType="VARCHAR"/>
            <result property="url" column="url" jdbcType="VARCHAR"/>
            <result property="publishTime" column="publish_time" jdbcType="TIMESTAMP"/>
            <result property="commentCount" column="comment_count" jdbcType="INTEGER"/>
            <result property="likeCount" column="like_count" jdbcType="INTEGER"/>
            <result property="readCount" column="read_count" jdbcType="INTEGER"/>
            <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
            <result property="creator" column="creator" jdbcType="VARCHAR"/>
            <result property="updateTime" column="update_time" jdbcType="TIMESTAMP"/>
            <result property="updater" column="updater" jdbcType="VARCHAR"/>
            <result property="remark" column="remark" jdbcType="VARCHAR"/>
    </resultMap>

    <sql id="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=true
    username: 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: true
  global-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 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: '/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

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!