SpringCloud RestTemplate作为负载均衡器客户端

2023-06-08 10:44 更新

RestTemplate​可以自动配置为在后台使用负载均衡器客户端。要创建负载均衡的​RestTemplate​,请创建​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不再通过自动配置创建。各个应用程序必须创建它。

URI需要使用虚拟主机名(即服务名,而不是主机名)。Ribbon客户端用于创建完整的物理地址。有关如何设置RestTemplate的详细信息,请参见RibbonAutoConfiguration

 重要

为了使用负载均衡的​RestTemplate​,您需要在类路径中具有负载均衡器实现。推荐的实现是​BlockingLoadBalancerClient​-添加​org.springframework.cloud:spring-cloud-loadbalancer​以便使用它。​RibbonLoadBalancerClient​也可以使用,但是目前正在维护中,我们不建议将其添加到新项目中。

如果要使用​BlockingLoadBalancerClient​,请确保项目类路径中没有​RibbonLoadBalancerClient​,因为向后兼容的原因,默认情况下将使用它。


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号