Spring Boot Pushgateway 应用实战:完整指南
以下是一个简单的 Spring Boot Pushgateway 应用的示例代码:
- 创建一个 Spring Boot 项目并添加以下依赖:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_pushgateway</artifactId>
<version>0.11.0</version>
</dependency>
- 在 application.properties 中添加以下配置:
management.metrics.export.prometheus.enabled=true
management.endpoints.web.exposure.include=prometheus
- 创建一个 controller 类来处理 Pushgateway 请求:
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.prometheus.client.exporter.PushGateway;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PushGatewayController {
private final MeterRegistry meterRegistry;
private final PushGateway pushGateway;
private final String jobName;
private final String pushGatewayUrl;
private final Counter counter;
public PushGatewayController(MeterRegistry meterRegistry,
@Value('${pushgateway.job-name}') String jobName,
@Value('${pushgateway.url}') String pushGatewayUrl) {
this.meterRegistry = meterRegistry;
this.pushGateway = new PushGateway(pushGatewayUrl);
this.jobName = jobName;
this.pushGatewayUrl = pushGatewayUrl;
this.counter = Counter.builder('pushgateway_demo')
.description('A demo counter for Pushgateway')
.tag('job', jobName)
.register(meterRegistry);
}
@GetMapping('/increment')
public String increment() {
counter.increment();
pushMetricsToGateway();
return 'Counter incremented';
}
private void pushMetricsToGateway() {
try {
pushGateway.pushAdd(meterRegistry.getPrometheusRegistry().getSampleValue('pushgateway_demo', new String[]{'job'}, new String[]{jobName}));
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 在 application.properties 中添加以下 Pushgateway 相关配置:
pushgateway.job-name=pushgateway-demo
pushgateway.url=http://localhost:9091
- 在 Pushgateway 中创建一个 job,并通过以下命令启动 Pushgateway:
docker run -d -p 9091:9091 prom/pushgateway
-
启动 Spring Boot 应用程序并访问 http://localhost:8080/increment 来增加计数器的值,并将指标推送到 Pushgateway。
-
在 Pushgateway 的 Web UI 中查看指标:http://localhost:9091/metrics。您应该能够看到来自 Spring Boot 应用程序的指标。
原文地址: https://www.cveoy.top/t/topic/nVZI 著作权归作者所有。请勿转载和采集!