【SpringCloud-07】Ribbon

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
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pascalzhli

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值