负载均衡——Ribbon

文章目录

Ribbon,Nexflix发布的负载均衡器,有助于控制HTTP和TCP客户端的行为。基于某种负载均衡算法(轮询、随机登),自动地帮助服务消费者去请求。

当Ribbon和Eureka配合使用时,Ribbot可自动从Eureka Server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例。

对Ribbon理解

Ribbon和Eureka配合使用

项目引入Ribbon

java 复制代码
<dependency>
	<groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>

如果已经引入spring-cloud-starter-eureka,无需再次引人,里面已经包含该依赖

RestTemplate添加@LoadBalanced注解

只需添加@LoadBalanced就可为RestTemplate整合Ribbon,使其具备负载均衡能力

java 复制代码
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
    // 用于访问第三方网络接口
    return new RestTemplate();
}

注意

当Ribbon和Eureka配合使用时,会自动将虚拟主机名(可将其简单理解成为提供者的服务名)映射成微服务的网络地址,代码中记得替换

microservice-provider-user 替换 localhost:8000

java 复制代码
@GetMapping("user/{id}")
public User findById(@PathVariable Long id){
    return restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
}

自定义均衡方式

代码注册方式
java 复制代码
// 注意:该类不应该在主应用程序上下文的@ComponentScan 中,否则该类中的配置信息就被所有的@RibbonClient共享
// 注意:自定义算法不可以放在与注解 @ComponentScan 的同包或者子包下,否则不起作用
@Configuration
public class MySelfRule {
    @Bean
    public IRule ribbonRule(){
        System.out.println("hahahahah");
        // 负载均衡规则改为随机
        return new RandomRule();
    }
}

在主程序添加

java 复制代码
@RibbonClient(name = "microservice-provider-user", configuration = MySelfRule.class)
// @ComponentScan忽略指定包
// @ComponentScan(excludeFilters={@ComponentScan.Filter(type = FilterType.REGEX,pattern = "com.cloud.config.*")})
配置方式
java 复制代码
# 修改服务地址轮询策略,默认是轮询,可配置随机等
microservice-provider-user:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

Ribbon脱离Eureka使用

https://www.dandelioncloud.cn/article/details/1596843302127353857

报错:

Field loadBalancerClient in com.cloud.controller.MovieController required a bean of type 'org.springframework.cloud.client.loadbalancer.LoadBalancerClient' that could not be found.

相关推荐
XIAOHEZIcode20 小时前
Linux系统鼠标偏移常见原因以及修复方案
linux·运维·游戏
用户0328472220702 天前
如何搭建本地yum源(上)
运维
大树884 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠4 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质5 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
Inhand陈工5 天前
基于台达PLC与映翰通IG502的智慧水产养殖精准投喂与远程运维解决方案
运维·人工智能·物联网·阿里云·信息与通信
酣大智5 天前
ARP代理--工作原理
运维·网络·arp·arp代理
shushangyun_5 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
施努卡机器视觉5 天前
SNK施努卡侧滑门锁上滑轮总成自动化装配线,从零件到组件,全流程精密制造方案
运维·自动化·制造
AC赳赳老秦5 天前
用 OpenClaw 搭建服务器故障应急响应系统,自动处理 80% 常见运维故障
android·运维·服务器·python·rxjava·deepseek·openclaw