以下是使用Java通过Prometheus HTTP API获取主机CPU情况的示例代码:
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.HTTPResponse;
import io.prometheus.client.exporter.HttpConnectionFactory;
import io.prometheus.client.exporter.PushGateway;
import io.prometheus.client.hotspot.DefaultExports;
import io.prometheus.client.spring.boot.SpringBootMetricsCollector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@Component
public class MetricsExporter {
private static final String PUSHGATEWAY_HOST = "localhost";
private static final String PUSHGATEWAY_PORT = "9091";
private static final String JOB_NAME = "example-job";
private static final String INSTANCE_NAME;
@Autowired
private SpringBootMetricsCollector springBootMetricsCollector;
static {
String hostname = "";
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
// handle exception
}
INSTANCE_NAME = hostname;
}
@Bean
public void start() throws InterruptedException, ExecutionException {
DefaultExports.initialize();
// register Spring Boot metrics collector
springBootMetricsCollector.register();
// define Prometheus Metrics
Gauge cpuUsage = Gauge.build()
.name("cpu_usage")
.help("Current CPU usage")
.register();
// create a PushGateway instance with HTTP connection factory
PushGateway pushGateway = new PushGateway(PUSHGATEWAY_HOST + ":" + PUSHGATEWAY_PORT,
new HttpConnectionFactory());
// push metrics to the PushGateway every 10 seconds
while (true) {
try {
HTTPResponse response = pushGateway.pushAdd(cpuUsage, JOB_NAME, INSTANCE_NAME);
System.out.println("Pushed metrics to PushGateway. Status code: " + response.getStatus());
} catch (Exception e) {
// handle exception
}
TimeUnit.SECONDS.sleep(10);
}
}
}
在上面的代码中,我们首先使用DefaultExports.initialize()
方法初始化Prometheus Java客户端的默认指标(例如JVM内存使用情况、线程数等)。然后,我们使用SpringBootMetricsCollector
实例将Spring Boot应用程序的度量收集器注册到Prometheus客户端。接下来,我们定义了一个名为cpu_usage
的计量器,该计量器会记录当前主机的CPU使用情况。
然后,我们创建了一个PushGateway
实例,并使用pushAdd()
方法将CPU使用率指标推送到PushGateway。我们还定义了一个作业名(example-job
)和一个实例名(使用主机名)。最后,我们使用TimeUnit.SECONDS.sleep(10)
方法设置了一个10秒的循环周期,周期性地将CPU使用率指标推送到PushGateway。