增加自定义负载均衡实现类
package com.learning.springcloud.ribbon.rule;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class CustomRule extends AbstractLoadBalancerRule {
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
@Override
public Server choose(Object key) {
ILoadBalancer loadBalancer = this.getLoadBalancer();
// 获取当前请求的服务的实例
List<Server> reachableServers = loadBalancer.getReachableServers();
int random = ThreadLocalRandom.current().nextInt(reachableServers.size());
Server server = reachableServers.get(random);
return server;
}
}
配置自定义负载均衡策略
- 修改配置文件 application.yml
stock-service:
ribbon:
NFLoadBalancerRuleClassName: com.learning.springcloud.ribbon.rule.CustomRule
# NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule
饥饿加载负载均衡策略
ribbon:
eager-load:
# 开启 ribbon 饥饿记载
enabled: true
# 配置 需要饥饿加载的服务名,多个逗号分割
clients: stock-service
文章来源地址https://www.toymoban.com/news/detail-786392.html
文章来源:https://www.toymoban.com/news/detail-786392.html
到了这里,关于自定义负载均衡(Ribbon)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!