SpringCloud RestTemplate作為負載均衡器客戶端

2023-06-08 10:44 更新

?RestTemplate?可以自動配置為在后臺使用負載均衡器客戶端。要創(chuàng)建負載均衡的?RestTemplate?,請創(chuàng)建?RestTemplate @Bean?并使用?@LoadBalanced?限定符,如以下示例所示:

@Configuration
public class MyConfiguration {

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

public class MyClass {
    @Autowired
    private RestTemplate restTemplate;

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

 警告

?RestTemplate? bean不再通過自動配置創(chuàng)建。各個應用程序必須創(chuàng)建它。

URI需要使用虛擬主機名(即服務名,而不是主機名)。Ribbon客戶端用于創(chuàng)建完整的物理地址。有關如何設置RestTemplate的詳細信息,請參見RibbonAutoConfiguration。

 重要

為了使用負載均衡的?RestTemplate?,您需要在類路徑中具有負載均衡器實現(xiàn)。推薦的實現(xiàn)是?BlockingLoadBalancerClient?-添加?org.springframework.cloud:spring-cloud-loadbalancer?以便使用它。?RibbonLoadBalancerClient?也可以使用,但是目前正在維護中,我們不建議將其添加到新項目中。

如果要使用?BlockingLoadBalancerClient?,請確保項目類路徑中沒有?RibbonLoadBalancerClient?,因為向后兼容的原因,默認情況下將使用它。


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號