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

效果图:

第一次

第二次

第三次

相关推荐
砍材农夫6 小时前
spring-ai|Spring‑AI 2.0.0 新特性 + 入门教程
spring boot·spring·spring cloud
COOLMO研究AI14 小时前
Python 如何实现 AI API 的动态路由与多通道负载均衡:多账号与多供应商的高可用调度
人工智能·python·负载均衡
Java成神之路-1 天前
Spring Cloud 微服务契约先行:为什么 Controller 建议要实现 Feign 接口?
spring·spring cloud·微服务
vx-程序开发2 天前
springboot旅游推介平台---附源码24175
java·spring boot·python·spring cloud·eclipse·django·idea
暖核3 天前
Nginx 从入门到实践:部署、配置、反向代理与负载均衡全解
运维·nginx·负载均衡
黑泽明*3 天前
LVS-负载均衡全解析
运维·负载均衡·lvs
xianyuCcCcCCCcc3 天前
Nginx 深度解析:从基础架构到反向代理与负载均衡实战全解
linux·运维·nginx·bash·负载均衡
小马同学-4 天前
负载均衡-LVS全解析
运维·负载均衡·lvs
952364 天前
Spring-cloud配置中心
java·spring·spring cloud·微服务
国际云,接待4 天前
Nginx 后面接负载均衡,502/504 到底该先查哪里?
运维·nginx·负载均衡