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

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

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

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

  • RestTemplate+Ribbon
  • Feign

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

Ribbon:

1、controller层:使用RestTemplate

@RestController
public class DeptController_Consumer {
    private static final String REST_URL_PREFIX = "http://MICROSERVICECLOUD-DEPT";

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/consumer/dept/add")
    public boolean add(Dept dept) {
        return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class);
    }
}

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

@Configuration
public class ConfigBean //boot -->spring   applicationContext.xml --- @Configuration配置   ConfigBean = applicationContext.xml
{ 
    @Bean
    @LoadBalanced//开启客户端负载均衡 Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端       负载均衡的工具。
    public RestTemplate getRestTemplate()
    {
        return new RestTemplate();
    }

    //修改Ribbon的负载均衡算法(默认轮询)
    @Bean
    public IRule myRule()
    {
        //return new RoundRobinRule();
        //return new RandomRule();//达到的目的,用我们重新选择的随机算法替代默认的轮询。
        return new RetryRule();
    }
}

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

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

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

private int total = 0;          // 总共被调用的次数,目前要求每台被调用5次
private int currentIndex = 0;   // 当前提供服务的机器号
//要求:轮询每台服务器,每台服务器调用5次
if(total < 5)
{
    server = upList.get(currentIndex);
    total++;
}else {
    total = 0;
    currentIndex++;
    if(currentIndex >= upList.size())
    {
        currentIndex = 0;
    }
}

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

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

Feign:

面向接口编程,用法简单

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

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

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

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

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

总结:

知识都是相通的。

感谢您的阅读!

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐