一、Ribbon负载均衡
一个服务对应一个LoadBalancer,一个LoadBalancer只有一个Rule,LoadBalancer记录服务的注册地址,提供更新服务的注册地址,Rule提供从服务的注册地址中找出一个地址的规则。
二、 自定义负载均衡
本文自定义负载均衡规则提供根据指定URI优先转发到特定的机器的功能。
三、实现代码
(1)负载均衡实现类
public class MicroServiceLoadBalancer<T extends Server> extends DynamicServerListLoadBalancer<T> {public MicroServiceLoadBalancer() {}public MicroServiceLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping, ServerList<T> serverList, ServerListFilter<T> filter, ServerListUpdater serverListUpdater) {super(clientConfig, rule, ping, serverList, filter, serverListUpdater);}public MicroServiceLoadBalancer(IClientConfig clientConfig) {super(clientConfig);}@Overridepublic String toString() {StringBuilder sb = new StringBuilder("MicroServiceLoadBalancer:");sb.append(super.toString());sb.append("ServerList:" + String.valueOf(getServerListImpl()));return sb.toString();}
}
(2)application.yaml文件1配置
micro-service:ribbon:NFLoadBalancerClassName: com.mk.springcloud.gateway.loadbalance.MicroServiceLoadBalancer
(3)代码配置
public class MicroRibbonConfig {@Beanpublic ILoadBalancer microILoadBalancer(IClientConfig config, ServerList<Server> serverList, ServerListFilter<Server> serverListFilter, IRule rule, IPing ping, ServerListUpdater serverListUpdater) {return new MicroServiceLoadBalancer<>(config, rule, ping, serverList,serverListFilter, serverListUpdater);}}@RibbonClient(name = "micro-service", configuration = MicroRibbonConfig.class)
public class RibbonClientConfig {}