0

Actuator 管理 的检测RestTemplate,我们只需要注入RestTemplateBuilder来创建RestTemplatebean:

@Configuration
public class HttpClientConfiguration {
    private final RestTemplateBuilder restTemplateBuilder;

    // let Actuator manages the instrumentation
    public HttpClientConfiguration(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplateBuilder = restTemplateBuilder;
    }

    @Bean // let Sleuth intercept requests
    public RestTemplate createRestTemplate() {
        return restTemplateBuilder.build();
    }
}

如何OAuth2RestTemplate使用 HTTP 客户端 Mertics 支持创建 bean(内置 OAuth2)?

4

1 回答 1

2

我刚刚找到了一个解决方案:

@Configuration
@EnableOAuth2Client
public class OAuthClientConfig {
    private final MetricsRestTemplateCustomizer metricsRestTemplateCustomizer;

    public OAuthConfig(MetricsRestTemplateCustomizer metricsRestTemplateCustomizer) {
        this.metricsRestTemplateCustomizer=metricsRestTemplateCustomizer;
    }

    @Bean
    public OAuth2RestTemplate createOAuth2RestTemplate() {
        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(
                getClientCredentialsResourceDetails(), 
                new DefaultOAuth2ClientContext());
        metricsRestTemplateCustomizer.customize(restTemplate);
        return restTemplate;
    }

    private ClientCredentialsResourceDetails getClientCredentialsResourceDetails() {
        ClientCredentialsResourceDetails rd = new ClientCredentialsResourceDetails();
        rd.setClientId("my-client-id");
        rd.setClientSecret("my-client-secret");
        rd.setAccessTokenUri("https://my-idp.server/oauth2/token");
        return rd;
    }
}
于 2019-03-02T02:32:21.797 回答