Введение:
Prometheus - это набор инструментов для системного мониторинга и оповещения с открытым исходным кодом, изначально созданный на SoundCloud. С момента его создания в 2012 году многие компании и организации приняли его.
Prometheus присоединился к Cloud Native Computing Foundation в 2016 году в качестве второго размещенного проекта после Kubernetes.
Давайте начнем:
Если вы здесь, возможно, вы знакомы с Grizzly и Jetty Server. Приступая к работе с новой библиотекой, полезно иметь пример. Когда я начинал, у меня не было ни одного примера в Google, и я потратил день на поиск Prometheus с сервером Grizzly. Я решил написать об этом.
Шаг 1-: Зарегистрируйте класс ресурса
/** * Created by SinghBrijesh on 06/23/2019. */ import javax.ws.rs.Path import io.prometheus.client.Counter import io.prometheus.client.Histogram import javax.ws.rs.GET import javax.ws.rs.Produces import javax.ws.rs.core.MediaType @Path("/app") class ExampleResource { val counter = Counter.build() .name("requests_total") .help("Total number of requests.").register() val requestLatency = Histogram.build() .name("requests_latency_seconds"). help("Request latency in seconds.").register() @GET @Path("/message") @Produces(MediaType.APPLICATION_JSON) fun getThePrometheusMatrics ( ): String { counter.inc() // Start the histogram timer val requestTimer = requestLatency.startTimer() try { return "Hello World!" } finally { // Stop the histogram timer requestTimer.observeDuration() } } }
Шаг 2-: Запустите Grizzly Server и зарегистрируйте путь Prometheus в сервлете с помощью grizzly.servlet.WebappContext
/** * Created by SinghBrijesh on 06/23/2019. */ import io.prometheus.client.exporter.MetricsServlet import org.glassfish.grizzly.servlet.WebappContext import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory import org.glassfish.jersey.server.ResourceConfig import javax.ws.rs.core.UriBuilder fun main(args: Array<String>) { val config = ResourceConfig() val exampleResource = ExampleResource() config.register(exampleResource) val uri = UriBuilder.fromUri("http://0.0.0.0").port(8080).build() val server = GrizzlyHttpServerFactory.createHttpServer(uri, config, false) var webappContext = WebappContext("metricscontex") webappContext.addServlet("metrics Servlet", MetricsServlet()).addMapping("/metrics") webappContext.deploy(server) server.start() }
Шаг 3-: откройте URL-адрес http: // localhost: 8080 / app / message, см.
"Привет мир"
Шаг 4-: откройте URL-адрес http: // localhost: 8080 / metrics и увидите волшебство.
# HELP requests_total Total number of requests. # TYPE requests_total counter requests_total 1.0 # HELP requests_latency_seconds Request latency in seconds. # TYPE requests_latency_seconds histogram requests_latency_seconds_bucket{le="0.005",} 1.0 requests_latency_seconds_bucket{le="0.01",} 1.0 requests_latency_seconds_bucket{le="0.025",} 1.0 requests_latency_seconds_bucket{le="0.05",} 1.0 requests_latency_seconds_bucket{le="0.075",} 1.0 requests_latency_seconds_bucket{le="0.1",} 1.0 requests_latency_seconds_bucket{le="0.25",} 1.0 requests_latency_seconds_bucket{le="0.5",} 1.0 requests_latency_seconds_bucket{le="0.75",} 1.0 requests_latency_seconds_bucket{le="1.0",} 1.0 requests_latency_seconds_bucket{le="2.5",} 1.0 requests_latency_seconds_bucket{le="5.0",} 1.0 requests_latency_seconds_bucket{le="7.5",} 1.0 requests_latency_seconds_bucket{le="10.0",} 1.0 requests_latency_seconds_bucket{le="+Inf",} 1.0 requests_latency_seconds_count 1.0 requests_latency_seconds_sum 5.821E-6
Поздравляем !!!, теперь вы создали свой проект с помощью Prometheus и Grizzly Server. Я очень признателен вам за то, что вы нашли время и зашли так далеко. теперь вы можете отслеживать свой API.
Я надеюсь, что это помогает.