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

有两种办法实现:

办法一

@EnableDiscoveryClient@SpringBootApplicationpublic class NacosDiscoveryConsumerApplication {    public static void main(String[] args) {        SpringApplication.run(NacosDiscoveryConsumerApplication.class, args);    }    @Bean    public RestTemplate restTemplate(){        return new RestTemplate();    }}
@RestControllerpublic 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@SpringBootApplicationpublic class NacosDiscoveryConsumerApplication {    public static void main(String[] args) {        SpringApplication.run(NacosDiscoveryConsumerApplication.class, args);    }    @Bean    @LoadBalanced    public RestTemplate restTemplate(){        return new RestTemplate();    }}
@RestControllerpublic 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时就能有负载平衡的性能。

启动两个服务者;

一个是8086端口,一个是8085端口,而后调用消费者,能够看到轮询调用两个服务者:

如何替换负载平衡策略

Ribbon提供7种负载平衡策略能够抉择:

  • RandomRule

    • 随机策略
    • 随机抉择server
  • RoundRobinRule

    • 轮询策略
    • 依照程序抉择server
  • RetryRule

    • 重试策略
    • 在一个配置时间段内,当抉择server不胜利,则始终尝试抉择一个可用的server
  • BestAvailableRule

    • 最低并发策略
    • 一一考查server,如果server断路器关上,则疏忽,再抉择其中并发链接最低的server
  • AvailabilityFilteringRule

    • 可用过滤策略
    • 过滤掉始终失败并被标记为circuit tripped的server,过滤掉那些高并发链接的server(active connections超过配置的阈值)
  • ResponseTimeWeightedRule

    • 响应工夫加权重策略
    • 依据server的响应工夫调配权重,响应工夫越长,权重越低,被抉择到的概率也就越低。响应工夫越短,权重越高,被选中的概率越高,这个策略很贴切,综合了各种因素,比方:网络,磁盘,io等,都间接影响响应工夫
  • ZoneAvoidanceRule

    • 区域权重策略
    • 综合判断server所在区域的性能,和server的可用性,轮询抉择server并且判断一个AWS Zone的运行性能是否可用,剔除不可用的Zone中的所有server

Ribbon默认的负载平衡策略是ZoneAvoidanceRule,如果没有查看到Zone,那么理论应用的是RoundRobinRule。

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

注入一个实现IRule的bean即可

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

下面的NacosWeightRandomRule是本人实现Nacos权重负载平衡的策略,通过下面的配置能够批改Ribbon的负载平衡策略。

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

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

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

而后在启动类上增加以下注解:

@RibbonClient(name = "nacos-discovery-provider", configuration = NacosRule.class)
  • name,须要应用负载平衡策略的微服务名
  • configuration,负载平衡策略类