Nacos中默认继承Ribbon

    在上一篇文章基础上,Consumer模块配置类新增@LoadBalanced注解

    1. @Configuration
    2. public class ConsumerConfig {
    3. @Bean
    4. @LoadBalanced
    5. public RestTemplate getRestTemplate() {
    6. return new RestTemplate();
    7. }
    8. }

    ConsumerController改造

    1. @RestController
    2. public class ConsumerController {
    3. private final DiscoveryClient discoveryClient;
    4. private final RestTemplate restTemplate;
    5. //访问服务提供者服务的前缀,http://服务名
    6. private static final String REST_URL_PREFIX = "http://provider";
    7. @Autowired
    8. public ConsumerController(DiscoveryClient discoveryClient, RestTemplate restTemplate) {
    9. this.discoveryClient = discoveryClient;
    10. this.restTemplate = restTemplate;
    11. }
    12. @GetMapping("/instances")
    13. public List<ServiceInstance> getInstances() {
    14. return discoveryClient.getInstances("provider");
    15. }
    16. @GetMapping("/index")
    17. public String index() {
    18. return "consumer远程调用provier:" + this.restTemplate.getForObject(REST_URL_PREFIX + "/index", String.class);
    19. }
    20. }

    默认采用轮询算法,常用的还有随机和权重算法

    随机

    1. server:
    2. port: 9090
    3. # 负载均衡策略 服务名+ribbon+策略(不配置默认使用轮询策略)
    4. provider:
    5. ribbon:
    6. NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

    Nacos 权重

    1. public class NacosWeightedRule extends AbstractLoadBalancerRule {
    2. private static final Logger log = LoggerFactory.getLogger(NacosWeightedRule.class);
    3. @Autowired
    4. private NacosDiscoveryProperties nacosDiscoveryProperties;
    5. @Override
    6. public void initWithNiwsConfig(IClientConfig iClientConfig) {
    7. //读取配置文件
    8. }
    9. @Override
    10. public Server choose(Object o) {
    11. ILoadBalancer loadBalancer = this.getLoadBalancer();
    12. BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) loadBalancer;
    13. //获取要请求的微服务名称
    14. String name = baseLoadBalancer.getName();
    15. //获取服务发现的相关API
    16. NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
    17. try {
    18. Instance instance = namingService.selectOneHealthyInstance(name);
    19. log.info("选择的实例是port={},instance={}", instance.getPort(), instance);
    20. return new NacosServer(instance);
    21. } catch (NacosException e) {
    22. e.printStackTrace();
    23. return null;
    24. }
    25. }
    26. }
    1. server:
    2. port: 9090
    3. # 负载均衡策略 服务名+ribbon+策略(不配置默认使用轮询策略)
    4. provider:
    5. ribbon:
    6. NFLoadBalancerRuleClassName: com.godfrey.configuration.NacosWeightedRule

    默认权重都是1,修改权重再进行测试

    Spring Cloud Alibaba 03:Ribbon负载均衡 - 图1