简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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