SpringCloud RestTemplate作為負(fù)載均衡器客戶(hù)端

2023-06-08 10:44 更新

?RestTemplate?可以自動(dòng)配置為在后臺(tái)使用負(fù)載均衡器客戶(hù)端。要?jiǎng)?chuàng)建負(fù)載均衡的?RestTemplate?,請(qǐng)創(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不再通過(guò)自動(dòng)配置創(chuàng)建。各個(gè)應(yīng)用程序必須創(chuàng)建它。

URI需要使用虛擬主機(jī)名(即服務(wù)名,而不是主機(jī)名)。Ribbon客戶(hù)端用于創(chuàng)建完整的物理地址。有關(guān)如何設(shè)置RestTemplate的詳細(xì)信息,請(qǐng)參見(jiàn)RibbonAutoConfiguration。

 重要

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

如果要使用?BlockingLoadBalancerClient?,請(qǐng)確保項(xiàng)目類(lèi)路徑中沒(méi)有?RibbonLoadBalancerClient?,因?yàn)橄蚝蠹嫒莸脑?,默認(rèn)情況下將使用它。


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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)