一 .概述
在实际的微服务的环境下,我们的微服务都集群部署,也就是说,我们的一个消费者想要调用producer的时候,实际上可以调用多个生产者.
在sprigncloud之中,为我们提供了客户端的负载工具,Ribbon,这个组件可以帮助我们实现客户端负载均衡.
二 .注意点
在微服务之中,每一个微服务的名称实际上是至关重要的.我们通过微服务的名称了进行不同微服务的区分和功能描述.
三 .搭建Ribbon的环境
[1]添加依赖内容
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency>
[2]修改启动类
@SpringBootApplication @EnableEurekaClient("cloud-producer") @RibbonClient public class ConsumerStarter { public static void main(String[] args) { SpringApplication.run(ConsumerStarter.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }
[3]修改方法调用
@GetMapping("user/{id}") public User queryUser(@PathVariable("id") int id) { return restTemplate.getForObject("http://CLOUD-PRODUCER/user/"+id, User.class); }
现在我们调用微服务的时候,使用的微服务的名称来进行调用的,在实际的情况下,Ribbon会按照自己的负载均衡策略进行调用.
三 .环境的测试
[1]将我们的服务端启动两遍,分别使用8000和8001端口完成.
[2]启动服务的消费者
然后进行调用,我们会发现结果会进行不断的变化.
实际上默认情况下,Ribbon采用的就是轮训的方式,下一次,我们使用Ribbon的自定义化的内容进行配置.