文章目录
1、Ribbon简介
1、什么是Ribbon?
2、Ribbon有什么作用?
主要用来实现客户端的负载均衡
-
集中式负载均衡(Nginx)
-
进程内负载均衡(Ribbon)
在之前的章节中,服务提供者通过使用Eureka集群(7001、7002) + 服务提供者集群(8001、8002),默认可以达到负载均衡的效果,这是因为在注入restTemplate时添加了@LoadBalanced注解
且通过查看Maven依赖可以发现,eureka的jar包中默认引入了ribbon的依赖
3、一句话总结
Ribbon = RestTemplate + 负载均衡
4、Ribbon架构
Ribbon本质上就是一个软负载均衡的客户端组件
可以和其他需要使用的客户端结合使用,Eureka只是其中一种
5、Ribbon负载均衡策略
2、RestTemplate的使用
- getForObject到getForEntity
- postForObject到postForEntity
3、替换Ribbon默认的负载均衡策略
1、使用之前的consumer-order-80
模块
通过查看Maven依赖可以发现,eureka的jar包中默认引入了ribbon的依赖
因此不需要额外导入依赖,这里就使用原有的订单模块即可
2、自定义配置类
1、注意
由上面的注意可知,对Ribbon默认策略修改的自定义配置类必须保证不再主启动类所在的包中,类似于秒杀项目中将接口限流抽取出来,需要的时候再添加,相当于抽取出来,需要使用到自定义策略时再添加使用
2、包结构图
3、编写配置类
package indi.zhihuali.ribbon;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Random;
/**
* @ program: spring-cloud
* @ description:
* @ author: zhihua li
* @ create: 2021-09-07 15:30
**/
@Configuration
public class MyRule {
@Bean
// bean对象名不可以写为 myRule
public IRule myRibbonRule() {
// 将负载均衡策略设置为随机策略
return new RandomRule();
}
}
4、主启动类添加注解@RibbonClient(服务名,配置类名)
package indi.zhihuali.common;
import indi.zhihuali.ribbon.MyRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
/**
* @ program: spring-cloud
* @ description:
* @ author: zhihua li
* @ create: 2021-09-02 09:48
**/
@SpringBootApplication
@EnableEurekaClient
//注意下面的服务名必须大写,且MyRule通过@Bean注入的对象对象名不能是myRule
@RibbonClient(name = "PAYMENT-SERVICE", configuration = MyRule.class)
public class OrderMain80 {
public static void main(String[] args) { SpringApplication.run(OrderMain80.class, args);
}
}
5、测试
通过访问localhost/consumer/payment/get/2
可以发现访问到的数据并不再是8001、8002轮询了,而是随机
至此替换Ribbon默认负载均衡策略完成
4、轮询算法原理
从源码中也可以看出主要的思想就是取余+CAS