【微服务】Ribbon和Feign负载均衡

左手的ㄟ右手 2022-05-15 06:40 307阅读 0赞

前面讲的,我们用Eureka作为服务注册中心,在服务启动后,各个微服务会将自己注册到Eureka Server,服务间通过REST调用,那么服务之间如何做负载均衡的,在实际开发中我们该如何选择呢?

正题之前我们先来回忆一下,Dubbo中我们消费者是如何找到提供者的呢?
不错,我们用的是Dubbo的负载均衡。

那么在Spring Cloud中我们有Ribbon和Feign做负载均衡,这样看就不陌生了吧。

好的,言归正传,我们知道在Spring Cloud中服务间通过restful方式调用有两种方式:

  • RestTemplate+Ribbon
  • Feign

我们首先来看下两者的用法:

Ribbon:

1、controller层:使用RestTemplate

  1. @RestController
  2. public class DeptController_Consumer {
  3. private static final String REST_URL_PREFIX = "http://MICROSERVICECLOUD-DEPT";
  4. @Autowired
  5. private RestTemplate restTemplate;
  6. @RequestMapping(value = "/consumer/dept/add")
  7. public boolean add(Dept dept) {
  8. return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class);
  9. }
  10. }

2、可自定义负载均衡算法,如下:

  1. @Configuration
  2. public class ConfigBean //boot -->spring applicationContext.xml --- @Configuration配置 ConfigBean = applicationContext.xml
  3. {
  4. @Bean
  5. @LoadBalanced//开启客户端负载均衡 Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端 负载均衡的工具。
  6. public RestTemplate getRestTemplate()
  7. {
  8. return new RestTemplate();
  9. }
  10. //修改Ribbon的负载均衡算法(默认轮询)
  11. @Bean
  12. public IRule myRule()
  13. {
  14. //return new RoundRobinRule();
  15. //return new RandomRule();//达到的目的,用我们重新选择的随机算法替代默认的轮询。
  16. return new RetryRule();
  17. }
  18. }

2.1如果要根据自己的需求定义,可抽出一个MyRule类:

  1. public class MySelfRule {
  2. @Bean
  3. public IRule myRule(){
  4. // return new RetryRule();//重试(轮询) 如果其中一台宕机,它会试着轮询它,轮询几次后就放弃这台宕机的机器了
  5. return new RandomRule_ZY();
  6. }
  7. }

定义RandomRule_ZY():必须继承AbstractLoadBalancerRule:
核心代码:

  1. private int total = 0; // 总共被调用的次数,目前要求每台被调用5次
  2. private int currentIndex = 0; // 当前提供服务的机器号
  3. //要求:轮询每台服务器,每台服务器调用5次
  4. if(total < 5)
  5. {
  6. server = upList.get(currentIndex);
  7. total++;
  8. }else {
  9. total = 0;
  10. currentIndex++;
  11. if(currentIndex >= upList.size())
  12. {
  13. currentIndex = 0;
  14. }
  15. }

最后还需在启动类上加@RibbonClient注解:
加configuration:

  1. @RibbonClient(name = "MICROSERVICECLOUD-DEPT",configuration = MySelfRule.class)
  2. public class DeptConsumer80_App {
  3. public static void main(String[] args) {
  4. SpringApplication.run(DeptConsumer80_App.class,args);
  5. }
  6. }

Feign:

面向接口编程,用法简单

  1. @FeignClient(value = "MICROSERVICECLOUD-DEPT")
  2. public interface DeptClientService {
  3. @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
  4. public boolean add(Dept dept);
  5. }

可结合Hystrix实现服务熔断、降级。

项目中我们选用了Feign,原因有几点:

  • Feign本身集成了Ribbon
  • 它是声明式的伪http客户端,写起来清晰,方便
  • Feign是基于接口的注解的编程方式,更简便

最后附一张图吧:
这里写图片描述

总结:

知识都是相通的。

感谢您的阅读!

发表评论

表情:
评论列表 (有 0 条评论,307人围观)

还没有评论,来说两句吧...

相关阅读