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这两个模块的访问模式切换到了随机访问模式,随机地返回了结果

效果图:

第一次

第二次

第三次

相关推荐
nvd1116 小时前
GCP L4 Passthrough 负载均衡器“假死超时”深度排查复盘
运维·php·负载均衡
nvd1116 小时前
GCP 4层 外部网络负载均衡器深度解析
运维·网络·负载均衡
陈聪.18 小时前
HAProxy 知识整理:从负载均衡原理到实战配置
运维·负载均衡
看昭奚恤哭1 天前
平滑加权轮询负载均衡的底层逻辑
运维·负载均衡
史呆芬1 天前
分布式事务实战:微服务跨服务数据一致性解决方案
java·后端·spring cloud
niaiheni1 天前
红队实战:记一次Spring Cloud Gateway SpEL表达式注入到哥斯拉内存马(CVE-2022-22947)
web安全·spring cloud·网络安全
小张同学a.2 天前
LAMP架构2
linux·运维·网络·架构·负载均衡
zzzll11112 天前
Spring Cloud 微服务:从入门到实践
spring·spring cloud·微服务
Devin~Y2 天前
从本地生活电商到 AI RAG:互联网大厂 Java 面试场景完整实战
java·spring boot·redis·elasticsearch·spring cloud·kafka·rag
小罗水3 天前
第11章 PostgreSQL + pgvector 向量检索
java·数据库·spring cloud·微服务