Spring Cloud Commons教程(二)Spring RestTemplate做为负载平衡器客户端

RestTemplate能够自动配置为使用功能区。要建立负载平衡RestTemplate建立RestTemplate @Bean并使用@LoadBalanced限定符。html

警告 经过自动配置再也不建立RestTemplate bean。它必须由单个应用程序建立。 @Configuration public class MyConfiguration {spring

@LoadBalanced
@Bean
RestTemplate restTemplate() {
    return new RestTemplate();
}
复制代码

}spa

public class MyClass { @Autowired private RestTemplate restTemplate;rest

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

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

重试失败的请求cdn

负载平衡RestTemplate能够配置为重试失败的请求。默认状况下,该逻辑被禁用,您能够经过将Spring重试添加到应用程序的类路径来启用它。负载平衡RestTemplate将符合与重试失败请求相关的一些Ribbon配置值。若是要在类路径中使用Spring重试来禁用重试逻辑,则能够设置spring.cloud.loadbalancer.retry.enabled=false。您可使用的属性是client.ribbon.MaxAutoRetries,client.ribbon.MaxAutoRetriesNextServer和client.ribbon.OkToRetryOnAllOperations。请参阅Ribbon文档 ,了解属性的具体内容。htm

注意 上述示例中的client应替换为您的Ribbon客户端名称。blog

源码来源:http://minglisoft.cn/honghu/technology.html文档

相关文章
相关标签/搜索