spring cloud Ribbon

参考:https://www.jianshu.com/p/1bd66db5dc46

Ribbon 是什么

spring cloud ribbon 是一个基于HTTP 和 TCP 的客户端负载均衡工具,它基于 NetFlix Ribbon 实现。通过spring cloud 封装,可以将面向

服务的REST 模板请求自动转换为客户端负载均衡的服务调用。

RestTenolate 实现访问

方式一:将url写死

RestTemplate restTemplate = new RestTemplate();
String response =restTemplate.getForObject("http://localhost:8090/msg",String.class);

方式二:动态获取host + port

@Autowired
private LoadBalancerClient loadBalancerClient;

RestTemplate restTemplate = new RestTemplate(); ServiceInstance serviceInstance = loadBalancerClient.choose("product"); String url = String.format("http://%s:%s",serviceInstance.getHost(),serviceInstance.getPort())+"/msg"; String response = restTemplate.getForObject(url,String.class);

方式三:

写一个配置类
@Component
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return  new RestTemplate();
    }
}
@Autowired
private RestTemplate restTemplate;
String response
= restTemplate.getForObject("http://product/msg",String.class);
原文地址:https://www.cnblogs.com/baizhuang/p/10560094.html