参考:https://blog.csdn.net/chengqiuming/article/details/80711168
Ribbon是Netflix发布的负载均衡器,它有助于控制HTTP和TCP的客户端的行为。为Ribbon配置服务提供者地址后,Ribbon就可基于某种负载均衡算法,自动地帮助服务消费者去请求。Ribbon默认为我们提供了很多负载均衡算法,例如轮询、随机等。当然,我们也可为Ribbon实现自定义的负载均衡算法。
在Spring Cloud中,当Ribbon与Eureka配合使用时,Ribbon可自动从Eureka Server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例。展示了Ribbon与Eureka配合使用时的架构
负载均衡又区分了两种类型:
graph TD 服务消费者-->ribbon ribbon-->服务清单1 ribbon-->服务清单2 ribbon-->服务清单3 服务清单1-->eureka里的服务1 服务清单2-->eureka里的服务2 服务清单3-->eureka里的服务3
@EnableDiscoveryClient @SpringBootApplication public class ConsumerMovieApplication { @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ConsumerMovieApplication.class, args); } }
@RestController public class MovieController { private static final Logger LOGGER = LoggerFactory.getLogger(MovieController.class); @Autowired private RestTemplate restTemplate; @Autowired private LoadBalancerClient loadBalancerClient; @GetMapping("/user/{id}") public User findById(@PathVariable Long id) { //VIP:virtual IP return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class); } @GetMapping("/log-user-instance") public void logUserInstance() { ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user"); // 打印当前选择的是哪个节点 MovieController.LOGGER.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort()); } }
server: port: 8010 spring: application: name: microservice-consumer-movie eureka: client: serviceUrl: defaultZone:http://localhost:8761/eureka/ instance: prefer-ip-address: true