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

效果图:

第一次

第二次

第三次

相关推荐
努力发光的程序员20 小时前
互联网大厂Java面试故事:Spring Boot与微服务全栈技术实战问答
java·spring boot·spring cloud·微服务·kafka·hibernate·面试技巧
椰椰椰耶21 小时前
[SpringCloud][8]Spring Cloud LoadBanlancer快速上手以及LoadBalancer原理
后端·spring·spring cloud
源远流长jerry1 天前
LVS 与 Nginx 负载均衡:从原理到生产实战
运维·网络·网络协议·tcp/ip·nginx·负载均衡·lvs
牧羊狼的狼1 天前
浅谈电商下单微服务流程
spring·spring cloud·微服务
魏杨杨2 天前
被流量逼出来的架构:从一台服务器到云原生的 17 次蜕变 —— 集群、缓存、MQ、微服务、Docker、K8S 的前世今生
微服务·k8s·负载均衡·ddd·分部署
Devin~Y2 天前
大厂Java面试实录:Spring Boot微服务 + Redis缓存 + Kafka消息队列 + Prometheus链路追踪 + RAG向量检索
java·spring boot·redis·spring cloud·kafka·rabbitmq·spring mvc
Mr.Java.2 天前
Spring AI MCP Server分布式翻车现场:Streamable协议的甜蜜与危险,以及无状态救赎
java·后端·spring·ai·负载均衡
Flittly3 天前
【日常小问】Spring Cloud Gateway 5.x 跨域和路由配置踩坑实录
java·spring boot·spring cloud
wljt3 天前
为什么要使用Spring Cloud,而不是HTTP直接调用接口?
spring·http·spring cloud