一、使用场景当一个服务具有多个实例时我们希望流量可以合理的分配到多个实例中此时我们可以使用 LoadBalancer 来实现负载均衡基于上篇博客我们再启动2个product-service实例接下来演示启动多个实例方法1、打开service2、右键要复制的实例选择 Copy Configuration3、改名并点击 modify options4、选择 add VM options5、添加 VM options: -Dserver.port 9091(9091为服务启动的端口号,可根据自己的情况进行修改)同样的操作可以再启动多个实例观察 Eureka可以看到新启动的实例但是此时我们启动服务发现远程调用的都是同一台机器此时我们可以使用 LoadBalancer 来实现均衡调用多台机器二、使用方式1、给 RestTemplate 这个 Bean 添加 LoadBalanced 注解package com.linzhixin.order.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; LoadBalancerClient(name product-service, configuration CustomLoadBalancerConfiguration.class) Configuration public class BeanConfig { Bean LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }2、修改 IP 端口号为服务名称public OrderInfo selectOrderById(Integer orderId) { OrderInfo orderInfo orderMapper.selectOrderById(orderId); //String url http://127.0.0.1:9090/product/ orderInfo.getProductId(); String url http://product-service/product/ orderInfo.getProductId(); ProductInfo productInfo restTemplate.getForObject(url, ProductInfo.class); orderInfo.setProductInfo(productInfo); return orderInfo; }3、按照上述方式启动多个 product-service 实例4、测试负载均衡连续多次发起请求http://127.0.0.1:8080/order/1观察 product-service 的日志可以发现请求在多个实例上都有分配​还可以切换负载均衡策略这里提供参考官网地址Spring Cloud LoadBalancer :: Spring Cloud Commons