Home > Net >  how to fetch metrics data from prometheus and use it within java springboot App?
how to fetch metrics data from prometheus and use it within java springboot App?

Time:09-05

I want to create an Alarm when CPU memory/Hard Disk Memory is full. I am using spring-boot f/w along with Prometheus. I can view all metrics details on HTTP requests:- http://localhost:9090/actuator/prometheus. but IDK how can I fetch the data from Prometheus in my project to raise an alarm or to do any action.

your suggestion/links will be more valuable. Thank you.

CodePudding user response:

You can scrap metrics from your actuator endpiont in the same way as Prometheus do it. I use OkHttpClient for that. Example of my client:

OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .followRedirects(false)
                .protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE))
                .build();

All settings are optional. But pay attention to the protocol - it should be the same as on your application's server.

After that you need to build url:

String url = "http://localhost:9090/actuator/prometheus?includedNames=<nameOfThePropertyThatYouNeed>";

You can include here more than 1 property:

String url = "http://localhost:9090/actuator/prometheus?includedNames=<propertyNameOne>,<propertyNameTwo>,<propertyNameThree>";

After that you make request:

Request request =new Request.Builder()
                .url(url)
                .get()
                .build();
Response response = client.newCall(request).execute();
String responseBody = response.body().string();

Now you need to parse responseBody. Do it in the way as Prometheus does it and use classes of Prometheus:

InputStream inputStream = new ByteArrayInputStream(responseBody.getBytes())
CollectorPrometheusMetricsWalker walker = new CollectorPrometheusMetricsWalker();
PrometheusMetricsProcessor<MetricFamily> processor = new TextPrometheusMetricsProcessor(inputStream, walker);
processor.walk();
List<MetricFamily> metricList = walker.getAllMetricFamilies();

MetricFamily object stores all metrics with the same name but with different tags. Use metricFamily.getMetrics() to get List<Metric> Use metric.getValue() to get the value of metric.

CodePudding user response:

You should use AlertManager that is part of Prometheus suit.

  • Related