写一个springboot的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/eEWG 著作权归作者所有。请勿转载和采集!