Search code examples
javaspring-bootprometheusresttemplatespring-boot-actuator

How to make custom RestTemplate to instrument with standard Spring Boots' Prometheus RestTemplate metrics when using SimpleClientHttpRequestFactory?


According to the docs, the standard http client metrics are grabbed if the RestTemplate is created using RestTemplateBuilder and then injected. However, we have a custom RestTemplate bean initialization that uses no RestTeplateBuilder, but instead RestTemplate is initiated with new and the SimpleClientHttpRequestFactory is passed as the parameter.

@Bean(name = "RestTemplateWithoutTimeOut")
    public RestTemplate restTemplateWithoutTimeOut() {
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        int timeout = 5 * 60 * 1000;
        simpleClientHttpRequestFactory.setConnectTimeout(timeout);
        simpleClientHttpRequestFactory.setReadTimeout(timeout);
        RestTemplate restTemplate = new RestTemplate(simpleClientHttpRequestFactory);
        restTemplate.setErrorHandler(new ErrorHandler());
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        interceptors.add(new LoggingInterceptor());
        interceptors.add(new SecureInterceptor());
        return restTemplate;
    }

How can we inject metrics collector (the same metrics as are collected by default) for that kind of RestTemplate initialization?


Solution

  • The RestTemplateBuilder exposes methods for customizing essentially every knob that's available on RestTemplate. You can just call requestFactory and pass your customized factory, then build a RestTemplate instance that has all of the usual instrumentation.