简体   繁体   English

使用 Jax-Rs 将 Prometheus Metrics Endpoint 添加到 Java 应用程序

[英]Add Prometheus Metrics Endpoint to Java App Using Jax-Rs

I'm trying to add a Prometheus metrics exporter to my Java app.我正在尝试向我的 Java 应用程序添加 Prometheus 指标导出器。 The app is currently using javax.ws.rs to define REST endpoints.该应用程序当前使用javax.ws.rs来定义 REST 端点。

For example:例如:

Import javax.ws.rs.*; 
Import javax.ws.rs.core.MediaType; 
Import javax.ws.rs.core.Response;

@GET
@Path(“/example”)
@Timed 
Public Response example(@QueryParam(“id”) Integer id) { 
   return Response.ok(“testing”)
}

All the examples I found for setting up Prometheus in Java are using Spring.我找到的在 Java 中设置 Prometheus 的所有示例都使用 Spring。 They suggest the following:他们建议如下:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import io.prometheus.client.exporter.HTTPServer;
import java.io.IOException;  

@SpringBootApplication 
public class App {  
   public static void main(String[] args) { 
      SpringApplication.run(App.class, args);  
      try { 
          HTTPServer server = new HTTPServer(8081);
      } catch (IOException e) { e.printStackTrace(); } 
   }  
}

Is there a way I can simply define a new endpoint in my current setup, for example:有没有一种方法可以在我当前的设置中简单地定义一个新端点,例如:

@GET
@Path(“/metrics”)
@Timed 
Public Response example { 
   return Response.ok(“return prom metrics here”)
}

Without having to introduce Spring into the stack?无需将Spring引入堆栈?

This can be done as follows:这可以按如下方式完成:

import io.prometheus.client.Counter; 
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.TextFormat;

CollectorRegistry registry = new CollectorRegistry(); 

Counter exCounter = Counter.build().name(“example”).register(registry);

@GET
@Path(“/metrics”)
Public String getMetrics() { 
  Writer writer = new StringWriter(); 
  try { 
     TextFormat.write004(writer, registry.metricFamilySamples()); 
     return writer.toString(); 
  } catch (IOException e) { 
     return “error”;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM