Springboot2.0.8使用pushgateway推送到prometheus

Springboot2.0.8使用pushgateway推送到prometheus

本文介绍Springboot2.0.8使用pushgateway推送到prometheus
请添加图片描述

环境

springboot2.0.8.RELEASE
spring-cloud-dependenciesFinchley.SR4
micrometer-registry-prometheus1.0.9
simpleclient_pushgateway0.9.0
Prometheusv2.4.0

prometheus:v2.4.0 查看的1.8的文档

1.配置pushgateway环境

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 http://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.0.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.dalaoyang</groupId>
    <artifactId>springcloud_prometheus_pushgateway</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springcloud_prometheus_pushgateway</name>
    <description>springcloud_prometheus_pushgateway</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_pushgateway</artifactId>
            <version>0.9.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

yml

server:
  port: 9889

spring:
  application:
    name: springcloud_prometheus_pushgateway

management:
  endpoints:
    web:
      exposure:
        include: "*"
        exclude: env,beans
  endpoint:
    metrics:
      enabled: true
    prometheus:
      enabled: true
  metrics:
    tags:
      application: ${spring.application.name}
    export:
      prometheus:
        pushgateway:
          #PUSHGATEWAY address
          baseUrl: 192.168.0.100:9091
          # Push cycle
          pushRate: 15s
          #job definition name
          job : ${spring.application.name}
          # Enable push
          enabled: true

SpringcloudPrometheusPushgatewayApplication 启动类

package com.liuhm;

import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class SpringcloudPrometheusPushgatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudPrometheusPushgatewayApplication.class, args);
    }

    @Bean
    MeterRegistryCustomizer<MeterRegistry> configurer(
            @Value("${spring.application.name}") String applicationName) {
        return (registry) -> registry.config().commonTags("application", applicationName);
    }
}

当前spring-boot-starter-parentt版本比较低需要单独写一个配置类用于推送信息

PushgatewayConfiguration

package com.liuhm.config;

import io.micrometer.core.annotation.Incubating;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.PushGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.AllNestedConditions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.PreDestroy;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author liuhaomin
 * @date 2021/8/17
 */
@Configuration
@EnableConfigurationProperties(PushgatewayConfiguration.PushgatewayProperties.class)
public class PushgatewayConfiguration {

    @ConfigurationProperties(prefix = "management.metrics.export.prometheus.pushgateway")
    public static class PushgatewayProperties {
        /**
         * Enable publishing via a Prometheus Pushgateway.
         */
        private Boolean enabled = false;

        /**
         * Required host:port or ip:port of the Pushgateway.
         */
        private String baseUrl = "localhost:9091";

        /**
         * Required identifier for this application instance.
         */
        private String job;

        /**
         * Frequency with which to push metrics to Pushgateway.
         */
        private Duration pushRate = Duration.ofMinutes(1);

        /**
         * Push metrics right before shut-down. Mostly useful for batch jobs.
         */
        private boolean pushOnShutdown = true;

        /**
         * Delete metrics from Pushgateway when application is shut-down
         */
        private boolean deleteOnShutdown = true;

        /**
         * Used to group metrics in pushgateway. A common example is setting
         */
        private Map<String, String> groupingKeys = new HashMap<>();

        public Boolean getEnabled() {
            return enabled;
        }

        public void setEnabled(Boolean enabled) {
            this.enabled = enabled;
        }

        public String getBaseUrl() {
            return baseUrl;
        }

        public void setBaseUrl(String baseUrl) {
            this.baseUrl = baseUrl;
        }

        public String getJob() {
            return job;
        }

        public void setJob(String job) {
            this.job = job;
        }

        public Duration getPushRate() {
            return pushRate;
        }

        public void setPushRate(Duration pushRate) {
            this.pushRate = pushRate;
        }

        public boolean isPushOnShutdown() {
            return pushOnShutdown;
        }

        public void setPushOnShutdown(boolean pushOnShutdown) {
            this.pushOnShutdown = pushOnShutdown;
        }

        public boolean isDeleteOnShutdown() {
            return deleteOnShutdown;
        }

        public void setDeleteOnShutdown(boolean deleteOnShutdown) {
            this.deleteOnShutdown = deleteOnShutdown;
        }

        public Map<String, String> getGroupingKeys() {
            return groupingKeys;
        }

        public void setGroupingKeys(Map<String, String> groupingKeys) {
            this.groupingKeys = groupingKeys;
        }
    }

    static class PrometheusPushGatewayEnabledCondition extends AllNestedConditions {
        public PrometheusPushGatewayEnabledCondition() {
            super(ConfigurationPhase.PARSE_CONFIGURATION);
        }

        @ConditionalOnProperty(value = "management.metrics.export.prometheus.enabled", matchIfMissing = true)
        static class PrometheusMeterRegistryEnabled {
            //
        }

        @ConditionalOnProperty("management.metrics.export.prometheus.pushgateway.enabled")
        static class PushGatewayEnabled {
            //
        }
    }
    /**
     * Configuration for
     * <a href="https://github.com/prometheus/pushgateway">Prometheus
     * Pushgateway</a>.
     *
     * @author David J. M. Karlsen
     */
    @Configuration
    @ConditionalOnClass(PushGateway.class)
    @Conditional(PrometheusPushGatewayEnabledCondition.class)
    @Incubating(since = "1.0.0")
    public class PrometheusPushGatewayConfiguration {
        private final Logger logger = LoggerFactory.getLogger(PrometheusPushGatewayConfiguration.class);
        private final CollectorRegistry collectorRegistry;
        private final PushgatewayProperties pushgatewayProperties;
        private final PushGateway pushGateway;
        private final Environment environment;
        private final ScheduledExecutorService executorService;

        PrometheusPushGatewayConfiguration(CollectorRegistry collectorRegistry,
                                           PushgatewayProperties pushgatewayProperties, Environment environment) {
            this.collectorRegistry = collectorRegistry;
            this.pushgatewayProperties = pushgatewayProperties;
            this.pushGateway = new PushGateway(pushgatewayProperties.getBaseUrl());
            this.environment = environment;
            this.executorService = Executors.newSingleThreadScheduledExecutor((r) -> {
                final Thread thread = new Thread(r);
                thread.setDaemon(true);
                thread.setName("micrometer-pushgateway");
                return thread;
            });
            executorService.scheduleAtFixedRate(this::push, 0, pushgatewayProperties.getPushRate().toMillis(),
                    TimeUnit.MILLISECONDS);
        }

        void push() {
            try {
                pushGateway.pushAdd(collectorRegistry, job(), pushgatewayProperties.getGroupingKeys());
            } catch (UnknownHostException e) {
                logger.error("Unable to locate host '" + pushgatewayProperties.getBaseUrl()
                        + "'. No longer attempting metrics publication to this host");
                executorService.shutdown();
            } catch (Throwable t) {
                logger.error("Unable to push metrics to Prometheus Pushgateway", t);
            }
        }

        @PreDestroy
        void shutdown() {
            executorService.shutdown();
            if (pushgatewayProperties.isPushOnShutdown()) {
                push();
            }
            if (pushgatewayProperties.isDeleteOnShutdown()) {
                try {
                    pushGateway.delete(job(), pushgatewayProperties.getGroupingKeys());
                } catch (Throwable t) {
                    logger.error("Unable to delete metrics from Prometheus Pushgateway", t);
                }
            }
        }

        private String job() {
            String job = pushgatewayProperties.getJob();
            if (job == null) {
                job = environment.getProperty("spring.application.name");
            }
            if (job == null) {
                // There's a history of Prometheus spring integration defaulting the job name to
                // "spring" from when
                // Prometheus integration didn't exist in Spring itself.
                job = "spring";
            }
            return job;
        }
    }

}

2.Prometheus配置

在Prometheus中配置eureka地址(server),以及需要收集的服务(services)。

在/home/prometheus/prometheus 创建 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

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "rules/alert_rules.yml"
  # - "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
    static_configs:
    - targets: ['192.168.0.100:9090']
  - job_name: pushgateway
    static_configs:
      - targets: ['192.168.0.100:9091']
        labels:
          instance: pushgateway

3.启动pushgateway 和 Prometheus

在/home/prometheus 创建 docker-compose.yml

version: '3'
services:
  # prometheus
  prometheus:
    image: prom/prometheus:v2.4.0
    hostname: prometheus
    container_name: prometheus
    restart: always
    ports:
     - "9090:9090"
    volumes:
     - $PWD/prometheus:/etc/prometheus
     - $PWD/prometheus/data:/prometheus
    privileged: true
    command:
     - '--config.file=/etc/prometheus/prometheus.yml'
     - '--web.console.libraries=/etc/prometheus/console_libraries'
     - '--web.console.templates=/etc/prometheus/consoles'
     - '--storage.tsdb.path=/prometheus'
     - '--web.enable-lifecycle'
  pushgateway:
    image: prom/pushgateway
    hostname: pushgateway
    container_name: pushgateway
    restart: always
    ports:
     - "9091:9091"

4.测试

启动程序后,访问pushgateway http://192.168.0.100:9091/
请添加图片描述

访问pushgateway http://192.168.0.100:9090/targets

代码下载
请添加图片描述

好的,你想要了解如何在Spring Boot 2.7.9中整合Swagger2并使用com.github.xiaoymin的knife4j扩展库,是吗?我可以为你提供一些步骤。 首先,你需要在你的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.8</version> </dependency> ``` 然后,你需要在你的Spring Boot配置类中添加以下内容: ```java @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger2接口文档") .description("Swagger2接口文档") .termsOfServiceUrl("http://localhost:8080/") .version("1.0") .build(); } } ``` 这个配置类将创建一个名为"Swagger2接口文档"的文档,并扫描com.example.demo.controller包中的所有控制器。 最后,你可以在你的浏览器中访问http://localhost:8080/doc.html来查看生成的文档。 如果你想自定义Swagger UI的主题,你可以在application.properties中添加以下配置: ```properties # Swagger UI主题 knife4j.swaggerui.path=/doc.html knife4j.swaggerui.title=Swagger2接口文档 knife4j.swaggerui.description=Swagger2接口文档 knife4j.swaggerui.version=1.0 knife4j.swaggerui.contact.name=联系人姓名 knife4j.swaggerui.contact.email=联系人邮箱 knife4j.swaggerui.contact.url=联系人网址 knife4j.swaggerui.license.name=许可证名称 knife4j.swaggerui.license.url=许可证网址 knife4j.swaggerui.enable=true # 配置主题 knife4j.swaggerui.theme=flattop ``` 这将启用knife4j并使用flattop主题。 希望这些步骤对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liuhm~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值