3

I am using Spring Cloud Angel.SR4. My Configuration class for creating an OAuth2RestTemplate bean is as follows:

@Configuration
public class OAuthClientConfiguration {
    @Autowired
    private MyClientCredentialsResourceDetails resource;

    public OAuthClientConfiguration() {
    }

    @Bean
    @Qualifier("MyOAuthRestTemplate")
    public OAuth2RestTemplate restTemplate() {
        return new OAuth2RestTemplate(this.resource);
    }
}

This configuration is totally fine since I am using this RestTemplate in a Feign RequestInterceptor for injecting access tokens to the feign requests. The problem is that when I annotate an autowired OAuth2RestTemplate with @LoadBalanced the dependency injection engine raises a NoSuchBeanDefinitionException exception. For example, the following would raise an exception:

@LoadBalanced
@Autowired
@Qualifier("MyOAuthRestTemplate")
private OAuth2RestTemplate restTemplate;

and when I remove the @LoadBalanced, everything works fine. What is wrong with @LoadBalanced? Do I need any additional configurations (I already have @EnableEurekaClient)?

4

2 回答 2

3

我找到了解决方法。问题是我误解了@LoadBalanced注释。这只是自动创建的负载平衡RestTemplatebean 的限定符,它不会在注解周围创建代理RestTemplate以注入负载平衡能力。

看到这个https://github.com/spring-cloud/spring-cloud-commons/blob/v1.0.3.RELEASE/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer /LoadBalancerAutoConfiguration.java,我修改了我的OAuth2RestTemplatebean定义如下,它解决了这个问题。

@Bean
@Qualifier("MyOAuthRestTemplate")
public OAuth2RestTemplate restTemplate(RestTemplateCustomizer customizer) {
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(this.resource);
    customizer.customize(restTemplate);
    return restTemplate;
}
于 2016-01-20T21:02:02.987 回答
1

我在 Spring Cloud 中使用 @LoadBalanced 和 restTemplate,并在幕后使用功能区。

在 bean 定义中添加 @LoadBalanced 它的工作原理如下:

在我的课上我有

@Autowired  
@LoadBalanced  
@Qualifier("bookRepositoryServiceRestTemplate") private RestTemplate bookRepositoryServiceRestTemplate;

在我的配置类中,我有:

@Configuration
public class ServiceConfig {

    @Bean
    @LoadBalanced
    public RestTemplate bookRepositoryServiceRestTemplate(SpringClientFactory clientFactory, LoadBalancerClient loadBalancer){
        RibbonClientHttpRequestFactory ribbonClientHttpRequestFactory = new RibbonClientHttpRequestFactory(clientFactory,loadBalancer);
        return new RestTemplate(ribbonClientHttpRequestFactory);
    }
    ....

}

这对我有用

我希望这可以帮助

于 2016-03-07T21:41:27.877 回答