Ribbon负载均衡调用

一、概述

1、是什么

Spring Cloud Ribbon是基于Netflix Ribbon实现的一套善户屋 负疑均衡的工具。
简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户试的饮件负载均衡算法和服务调用,Ribbon客户就组件提供一系列完善的配置项如连接超时,重试等,简单的说,就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,Ribbon会自动的帮动你基于某种规则(如购单轮询,随机连接等)去连提这些机器,我们很容易使用Ribbon实现自定义的负载均衡算法。

2、官网资料

官网:https://github.com/Netflix/ribbon/wiki/Getting-Started
Ribbon目前也进入维护模式,未来使用SpringCloud loadBalancer替换
在这里插入图片描述

3、能干嘛

(1)LB(负载均衡)

在这里插入图片描述
在这里插入图片描述

(2)一句话

负载均衡+RestTemplate调用

二、Ribbon负载均衡演示

1、架构说明

Ribbon其实就是一个软负载均衡的客户端组件, 他可以和其他所需请求的客户端结合使用,和eureka结合只是其中一个实例

2、POM

spring-cloud-start-netflix-eureka自带spring-cloud-starter-ribbon

3、RestTemplate的使用

可发送get请求和post请求,getForObject方法/getForEntity方法和postForObject/postEntity
在这里插入图片描述

三、Ribbon核心组件IRule

1、IRule:根据特定算法从服务列表中选取一个要访问的服务

(1)轮询 com.netflix.loadbalancer.RoundRobinRule
(2)随机 com.netflix.loadbalancer.RandomRule
(3)先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内进行重试,获取可用的服务 com.netflix.loadbalancer.RetryRule
(4)对RoundRobinRule的扩展,响应速度越快的实例选择权重越多大,越容易被选择 WeightedResponseTimeRule
(5)会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务BestAvailableRule
(6)先过滤掉故障实例,再选择并发较小的实例 AvailabilityFilteringRule
(7)默认规则,复合判断server所在区域的性能和server的可用性选择服务器 ZoneAvoidanceRule

2、如何替换

(1)注意配置细节

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(2)新建package

在这里插入图片描述

(3)代码

package com.atguigu.myrule;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* 自定义负载均衡路由规则类
*
* @author liwei
* @date 2020/3/6 15:15
**/
@Configuration
public class MySelfRule {

   @Bean
   public IRule myRule() {
       // 定义为随机
       return new RoundRobinRule();
   }
}

(4)主启动类添加@RibbonClient

package com.atguigu.springcloud;

import com.atguigu.myrule.MySelfRule;
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;

/**
* @author zzyy
* @date 2020/02/18 17:20
**/
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
public class OrderMain80 {
   public static void main(String[] args) {
       SpringApplication.run(OrderMain80.class, args);
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值