Ribbon负载均衡

2020-10-13  本文已影响0人  危地马拉的大坑

上一段代码中使用了简单的消费者-服务者模式提供了最简单的微服务,使用Nacos做服务注册中心。Ribbon是带负载均衡的Http客户端。

有两种方法实现:

方法一

@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosDiscoveryConsumerApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
@RestController
public class HelloController {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;

    @GetMapping("/hello")
    public String HelloClient(String name){
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-discovery-provider");
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "hello?name=" + name, String.class);
    }
}

LoadBalancerClient类的choose负责查找合适的服务ip。

方法二

@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosDiscoveryConsumerApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
@RestController
public class HelloController {
    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/hello")
    public String HelloClient(String name){
        return restTemplate.getForObject("http://nacos-discovery-provider/hello?name=" + name, String.class);
    }
}

在注入RestTemplateBean时,同时添加@LoadBalanced注解,那么调用getForObject时就能有负载均衡的功能。

启动两个服务者

image-20201011110626187 image-20201011110643761

一个是8086端口,一个是8085端口,然后调用消费者,可以看到轮训调用两个服务者:

image-20201011110856606 image-20201011110916780

如何替换负载均衡策略

Ribbon提供7种负载均衡策略可以选择:

Ribbon默认的负载均衡策略是ZoneAvoidanceRule,如果没有检查到Zone,那么实际使用的是RoundRobinRule。

如何能更换负载均衡策略呢?

注入一个实现IRule的bean即可

@Configuration
public class NacosRule {

    @Bean
    public IRule iRule(){
        return new NacosWeightRandomRule();
    }
}

上面的NacosWeightRandomRule是自己实现Nacos权重负载均衡的策略,通过上面的配置可以修改Ribbon的负载均衡策略。

如果把上面的类放在@SpringBootApplication所在的包或子包下,那么所有的微服务远程访问都是用此负载均衡策略。

image-20201013102855953

如果只想把此负载均衡策略使用在某个微服务的请求上如何做呢?

把上面的类放在放在@SpringBootApplication所在的包或子包外

image-20201013103225113

然后在启动类上添加以下注解:

@RibbonClient(name = "nacos-discovery-provider", configuration = NacosRule.class)
上一篇 下一篇

猜你喜欢

热点阅读