我想将Prometheus指标暴露给端点。 我没有spring-boot,因此我需要自己公开指标。
我从以下示例代码中获取了
https://micrometer.io/docs/registry/prometheus#_configuring
PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/prometheus", httpExchange -> {
String response = prometheusRegistry.scrape(); (1)
httpExchange.sendResponseHeaders(200, response.getBytes().length);
try (OutputStream os = httpExchange.getResponseBody()) {
os.write(response.getBytes());
}
});
new Thread(server::start).start();
} catch (IOException e) {
throw new RuntimeException(e);
}
虽然可行,但我想避免使用sun软件包。有没有办法通过netty,okhttp或apache来做到这一点呢?
谢谢。
答案 0 :(得分:1)
您可以使用以下代码:
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(new MetricsServlet()), "/prometheus");
导入中没有sun软件包,只有Jetty和Prometheus Java client:
import io.prometheus.client.exporter.MetricsServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;