一、Ribbon负载均衡策略
一个服务对应一个LoadBalancer,一个LoadBalancer只有一个Rule,LoadBalancer记录服务的注册地址,Rule提供从服务的注册地址中找出一个地址的规则。
Ribbon提供七种负载均衡策略,默认的负载均衡策略是轮训策略。
二、 自定义负载均衡策略
本文自定义负载均衡规则提供根据指定URI优先转发到特定的机器的功能。
三、实现代码
(1)负载均衡策略实现类
public class MicroServiceLoadBalanceRule extends AbstractLoadBalancerRule {@Overridepublic void initWithNiwsConfig(IClientConfig iClientConfig) {}@Overridepublic Server choose(Object key) {ILoadBalancer lb = getLoadBalancer();if (lb == null) {return null;}List<Server> servers = lb.getReachableServers();if (servers.isEmpty()){return null;}RequestContext ctx = RequestContext.getCurrentContext();HttpServletRequest request = ctx.getRequest();String uri = request.getRequestURI();boolean specialApi = uri.startsWith("/api") ;// /api路径优先转发到指定的机器if(specialApi){String ip = "192.168.2.3";Server chooseServer = null;for (Server server : servers) {if (server.getHost().equals(ip)) {chooseServer = server;}}if(chooseServer == null){chooseServer = servers.stream().findFirst().orElse(null);}return chooseServer;}return servers.get(new Random().nextInt(servers.size()));}}
(2)application.yaml文件配置
micro-service:ribbon:NFLoadBalancerRuleClassName: com.mk.springcloud.gateway.loadbalance.MicroServiceLoadBalanceRule
(3) 代码配置
public class MicroRibbonConfig {@Beanpublic IRule microIRule(){return new MicroServiceLoadBalanceRule();}}@RibbonClient(name = "micro-service", configuration = MicroRibbonConfig.class)public class RibbonClientConfig {}
如果觉得《SpringCloud Ribbon(二)之自定义负载均衡策略IRule》对你有帮助,请点赞、收藏,并留下你的观点哦!