Spring Boot OAuth2RestTemplate和HTTP客户端指标

时间:2019-03-02 00:32:29

标签: spring-boot oauth-2.0 resttemplate spring-micrometer oauth2resttemplate

执行器管理RestTemplate的工具,我们只需要注入RestTemplateBuilder来创建RestTemplate bean:

@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();
    }
}

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

1 个答案:

答案 0 :(得分:1)

我刚刚找到了解决方法:

@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;
    }
}