SpringCloud 多個RestTemplate對象

2023-06-08 11:20 更新

如果您想要一個?RestTemplate?而不是負載均衡的,請創(chuàng)建一個?RestTemplate? bean并注入它。要訪問負載均衡的?RestTemplate?,請在創(chuàng)建?@Bean?時使用?@LoadBalanced?限定符,如以下示例所示:

@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("https://example.com", String.class);
    }
}

 重要

注意,在前面的示例中,在普通的RestTemplate聲明上使用了@Primary批注,以消除不合格的@Autowired注入的歧義。

 如果看到諸如java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89之類的錯誤,請嘗試注入RestOperations或設(shè)置spring.aop.proxyTargetClass=true。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號