Ribbon简介
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端 负载均衡工具
Ribbon 和 Nginx负载均衡区别
负载均衡介绍:
Nginx负载均衡和Ribbon区别:
Nginx是集中式
的负载均衡,Ribbon是进程内的负载均衡
Ribbon 负载均衡
Ribbon其实就是一个软负载均衡的客户组件,它可以和其他所需请求的客户端结合使用,和eureka结合只是其中一个实例
Ribbon 负载均衡架构原理图:
Ribbon负载均衡实例
Ribbon负载均衡的使用很简单:
Ribbon的使用就是 RestTemplate + @LoadBalanced 负载均衡的使用
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
许多注册中心都已经引入了 Ribbon组件
如:eureka客户端的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
所以我们不需要引入Ribbon 即可直接用
Ribbon核心组件 IRule
IRule接口源码如下:
package com.netflix.loadbalancer;
/**
* Interface that defines a "Rule" for a LoadBalancer. A Rule can be thought of
* as a Strategy for loadbalacing. Well known loadbalancing strategies include
* Round Robin, Response Time based etc.
*
* @author stonse
*
*/
public interface IRule{
/*
* choose one alive server from lb.allServers or
* lb.upServers according to key
*
* @return choosen Server object. NULL is returned if none
* server is available
*/
public Server choose(Object key);
public void setLoadBalancer(ILoadBalancer lb);
public ILoadBalancer getLoadBalancer();
}
IRule 接口的 是定义负载均衡规则的接口,IRule有许多落地的实现,如下图所示:
各个负载均衡的策略如下图所示:
Ribbon负载均衡策略的替换
Ribbon默认的负载均衡策略是轮询
修改为其他负载均衡策略步骤如下:(本例修改为随机即 RandomRule )
-
新创建一个包,该包不能在主启动类所在的包及其子报下,避免项目启动就被扫描:
-
在该包下新建配置类 如下:
import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.RandomRule; import org.springframework.context.annotation.Configuration; @Configuration public class MyRule { @Bean public IRule randomRule() { return new RandomRule(); } }
-
主启动类上添加
@RibbonClient
注意@RibbonClient 参数:
name = "SPRINGCLOUD-PAYMENT-PROVIDER"
:是注册中心某个服务名,
configuration = MyRule.class
:我们自己配置负载均衡策略@RibbonClient(name = "SPRINGCLOUD-PAYMENT-PROVIDER", configuration = MyRule.class) @EnableEurekaClient @EnableDiscoveryClient @SpringBootApplication public class SpringcloudConsumerOrderApplication {