Multiple RestTemplate objects

如果使RestTemplate不支持负载均衡,那么可以注入一个普通的RestTemplate bean。通过@LoadBalanced注解来创建支持负载均衡的RestTemplate

重要

注意下面的例子中在RestTemplate上声明的@Primary注解,这是为了避免在使用@Autowired进行注入时产生错误。

@Configuration
public class MyConfiguration {

    @LoadBalanced
    @Bean
    RestTemplate loadBalanced() {
        return new RestTemplate();
    }

    @Primary
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

public class MyClass {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    @LoadBalanced
    private RestTemplate loadBalanced;

    public String doOtherStuff() {
        return loadBalanced.getForObject("http://stores/stores", String.class);
    }

    public String doStuff() {
        return restTemplate.getForObject("http://example.com", String.class);
    }
}

如果遇到java.lang.IllegalArgumentException:Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89异常。尝试注入RestOperations,或者设置spring.aop.proxyTargetClass=true.

results matching ""

    No results matching ""