1.引入jar包
<!-- https://mvnrepository.com/artifact/io.prometheus/simpleclient -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient</artifactId>
<version>0.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.prometheus/simpleclient_hotspot -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_hotspot</artifactId>
<version>0.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.prometheus/simpleclient_common -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_common</artifactId>
<version>0.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2.自定义endpoint
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.Set;
@Endpoint(id="my-prometheus-endpoint")
@Configuration
public class MyPrometheusEndpoint {
@ReadOperation
public String endpoint() {
return this.writeRegistry(Collections.emptySet());
}
public String writeRegistry(Set<String> metricsToInclude) {
try {
Writer writer = new StringWriter();
TextFormat.write004(writer, CollectorRegistry.defaultRegistry.filteredMetricFamilySamples(metricsToInclude));
return writer.toString();
} catch (IOException var3) {
throw new RuntimeException("Writing metrics failed", var3);
}
}
}
3.yml文件添加endpoint
management:
endpoints:
web:
exposure:
include: my-prometheus-endpoint
4.使用
import io.prometheus.client.Counter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
private static final Counter requestTotal = Counter.build()
.name("pingMethodConter").help("pingMethodConter").register();
@GetMapping(value = "/ping")
public String ping(){
requestTotal.inc();
return "pong-"+System.currentTimeMillis();
}
}
5.访问
触发访问计数
http://localhost:9300/ping
查看计数统计
http://localhost:9300/actuator/my-prometheus-endpoint