SpringCloud系列(21)--更换Ribbon的负载均衡模式

前言:在上一篇文章中我们介绍了关于Ribbon的知识点已经如果去应用Ribbon,而本章节内容则是关于如何去切换Ribbon的负载均衡模式。


以下是上篇文章的部分内容,可以再看下熟悉下,方便后续理解

Ribbon工作架构图

Ribbon的负载均衡模式

(1)RoundRobinRule:轮询(如果不设置Ribbon的负载均衡模式,则默认位轮询模式)

(2)RandomRule:随机

(3)RetryRule:先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务

(4)WeightedResponseTimeRule:对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择

(5)BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务

(6)AvailabilityFilteringRule:先过滤掉故障实例,再选择并发较小的实例

(7)ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可用性选择服务器


1、在java文件夹下新建名为com.ken.myrule包

效果图:

2、在com.ken.myrule包下新建名为MySelfRule的自定义配置类

注:MySelfRule这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了。

效果图:

3、编写MySelfRule类
java 复制代码
package com.ken.myrule;

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

@Configuration
public class MySelfRule {
    
    @Bean
    public IRule myRule() {
        //负载均衡模式为随机
        return new RandomRule();
    }
    
}
4、编辑主启动类,指定访问CLOUD-PAYMENT-SERVICE服务时所使用的负载均衡模式
java 复制代码
package com.ken.springcloud;

import com.ken.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;

@SpringBootApplication
//标注为Eureka Client(服务注册中心)
@EnableEurekaClient
//指定访问服务名为CLOUD-PAYMENT-SERVICE的服务时,使用我们自定义的负载均衡模式
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain {

    public static void main(String[] args) {
        SpringApplication.run(OrderMain.class,args);
    }

}
5、分别启动eureka-server7001、eureka-server7002、provider-payment8001、provider-payment8002、consumer-order80,然后在浏览器地址栏输入http://localhost/consumer/get/1,通过调用consumer-order80模块接口的方式查看返回的结果得知consumer-order80模块对provider-payment8001、provider-payment8002这两个模块的访问模式切换到了随机访问模式,随机地返回了结果

效果图:

第一次

第二次

第三次

相关推荐
BioRunYiXue2 天前
使用docker分析高通量测序数据
java·数据库·人工智能·spring cloud·docker·tomcat·html
SL_staff3 天前
金融风控规则引擎的深度实践:JVS-Rules 四大原生能力解析
spring cloud·产品·全栈
萧瑟余晖3 天前
Spring Cloud配置中心与动态刷新详解
spring cloud·面试
网络小江3 天前
组网第27课:ARP 的能与不能——免费 ARP、代理 ARP 与 ARP 欺骗
服务器·网络·网络安全·负载均衡·免费arp
code_slave(码畜)3 天前
微服务架构落地:分库分表实战(下) —— 分布式主键、跨分片查询与分页聚合防坑
数据库·spring boot·分布式·spring cloud·微服务·架构·分库分表
萧瑟余晖3 天前
Spring Cloud综合实战与架构选型详解
spring·spring cloud·架构
萧瑟余晖3 天前
Spring Cloud Alibaba生态整合详解
spring·spring cloud·面试
萧瑟余晖4 天前
Spring Cloud分布式事务与链路追踪详解
分布式·spring·spring cloud
EDPJ5 天前
MoE 与推测解码(Speculative Decoding)加速:为什么慢、什么时候慢、怎么让它不慢?
llm·负载均衡·大语言模型·moe·推测解码(sd)