日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringCloud Ribbon实战以及Ribbon的源码浅析(四)

發(fā)布時間:2025/3/15 javascript 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringCloud Ribbon实战以及Ribbon的源码浅析(四) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Ribbon負載均衡的策略有下面幾種:

上面我們講解了Ribbon的默認輪詢負載均衡的算法

我們先看下Ribbon負載均衡的算法源碼:https://github.com/Netflix/ribbon/tree/master/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer? (Github上的源碼下載)

Ribbon負載均衡策略接口的源碼分析:

/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer;/*** Interface that defines a "Rule" for a LoadBalancer. A Rule can be thought of* as a Strategy for loadbalacing. Well known loadbalancing strategies include* Round Robin, Response Time based etc.* * @author stonse* */ public interface IRule{/** choose one alive server from lb.allServers or* lb.upServers according to key* * @return choosen Server object. NULL is returned if none* server is available */public Server choose(Object key);public void setLoadBalancer(ILoadBalancer lb);public ILoadBalancer getLoadBalancer(); }

下面就看下是應該用什么策略來設置負載均衡先看下抽象類測負載均衡策略類

/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer;import com.netflix.client.IClientConfigAware;/*** Class that provides a default implementation for setting and getting load balancer* @author stonse**/ public abstract class AbstractLoadBalancerRule implements IRule, IClientConfigAware {private ILoadBalancer lb;@Overridepublic void setLoadBalancer(ILoadBalancer lb){this.lb = lb;}@Overridepublic ILoadBalancer getLoadBalancer(){return lb;} }

getLoadBalancer();返回負載均衡器,具體的負載均衡器由具體的實現(xiàn)類繼承得到

?

下面我們看下負載均衡輪詢策略是怎么定義的(RoundRobinRule源碼分析)

/*** Copyright 2013 Netflix, Inc.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.**/ package com.netflix.loadbalancer;import com.netflix.client.config.IClientConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import java.util.List; import java.util.concurrent.atomic.AtomicInteger;/*** The most well known and basic load balancing strategy, i.e. Round Robin Rule.** @author stonse* @author Nikos Michalakis <nikos@netflix.com>**/ public class RoundRobinRule extends AbstractLoadBalancerRule {private AtomicInteger nextServerCyclicCounter;private static final boolean AVAILABLE_ONLY_SERVERS = true;private static final boolean ALL_SERVERS = false;private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);public RoundRobinRule() {nextServerCyclicCounter = new AtomicInteger(0);}public RoundRobinRule(ILoadBalancer lb) {this();setLoadBalancer(lb);}public Server choose(ILoadBalancer lb, Object key) {if (lb == null) {log.warn("no load balancer");return null;}Server server = null;int count = 0;while (server == null && count++ < 10) {List<Server> reachableServers = lb.getReachableServers();List<Server> allServers = lb.getAllServers();int upCount = reachableServers.size();int serverCount = allServers.size();if ((upCount == 0) || (serverCount == 0)) {log.warn("No up servers available from load balancer: " + lb);return null;}int nextServerIndex = incrementAndGetModulo(serverCount);server = allServers.get(nextServerIndex);if (server == null) {/* Transient. */Thread.yield();continue;}if (server.isAlive() && (server.isReadyToServe())) {return (server);}// Next.server = null;}if (count >= 10) {log.warn("No available alive servers after 10 tries from load balancer: "+ lb);}return server;}/*** Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.** @param modulo The modulo to bound the value of the counter.* @return The next value.*/private int incrementAndGetModulo(int modulo) {for (;;) {int current = nextServerCyclicCounter.get();int next = (current + 1) % modulo;if (nextServerCyclicCounter.compareAndSet(current, next))return next;}}@Overridepublic Server choose(Object key) {return choose(getLoadBalancer(), key);}@Overridepublic void initWithNiwsConfig(IClientConfig clientConfig) {} }

RoundRobinRule類通過繼承了AbstractLoadBalancerRule抽象類

就這樣實現(xiàn)了輪詢

?

有源碼可以知道

?

下面我在看下ILoadBalancer接口是怎么設置負載均衡器的(源碼分析)

/* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer;import java.util.List;/*** Interface that defines the operations for a software loadbalancer. A typical* loadbalancer minimally need a set of servers to loadbalance for, a method to* mark a particular server to be out of rotation and a call that will choose a* server from the existing list of server.* * @author stonse* */ public interface ILoadBalancer {/*** Initial list of servers.* This API also serves to add additional ones at a later time* The same logical server (host:port) could essentially be added multiple times* (helpful in cases where you want to give more "weightage" perhaps ..)* * @param newServers new servers to add*/public void addServers(List<Server> newServers);/*** Choose a server from load balancer.* * @param key An object that the load balancer may use to determine which server to return. null if * the load balancer does not use this parameter.* @return server chosen*/public Server chooseServer(Object key);/*** To be called by the clients of the load balancer to notify that a Server is down* else, the LB will think its still Alive until the next Ping cycle - potentially* (assuming that the LB Impl does a ping)* * @param server Server to mark as down*/public void markServerDown(Server server);/*** @deprecated 2016-01-20 This method is deprecated in favor of the* cleaner {@link #getReachableServers} (equivalent to availableOnly=true)* and {@link #getAllServers} API (equivalent to availableOnly=false).** Get the current list of servers.** @param availableOnly if true, only live and available servers should be returned*/@Deprecatedpublic List<Server> getServerList(boolean availableOnly);/*** @return Only the servers that are up and reachable.*/public List<Server> getReachableServers();/*** @return All known servers, both reachable and unreachable.*/public List<Server> getAllServers(); }

我可以看到這個負載均衡器的接口有下面四個實現(xiàn)類:

其中有一個抽象類負載均衡器AbstractLoadBalancer /* * * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.loadbalancer;import java.util.List;/*** AbstractLoadBalancer contains features required for most loadbalancing* implementations.* * An anatomy of a typical LoadBalancer consists of 1. A List of Servers (nodes)* that are potentially bucketed based on a specific criteria. 2. A Class that* defines and implements a LoadBalacing Strategy via <code>IRule</code> 3. A* Class that defines and implements a mechanism to determine the* suitability/availability of the nodes/servers in the List.* * * @author stonse* */ public abstract class AbstractLoadBalancer implements ILoadBalancer {public enum ServerGroup{ALL,STATUS_UP,STATUS_NOT_UP }/*** delegate to {@link #chooseServer(Object)} with parameter null.*/public Server chooseServer() {return chooseServer(null);}/*** List of servers that this Loadbalancer knows about* * @param serverGroup Servers grouped by status, e.g., {@link ServerGroup#STATUS_UP}*/public abstract List<Server> getServerList(ServerGroup serverGroup);/*** Obtain LoadBalancer related Statistics*/public abstract LoadBalancerStats getLoadBalancerStats(); }

選擇一個服務

裝載

下面我看下具體是怎么選擇的一個抽象類肯定會有很多是實現(xiàn)類其中一個是BaseLoadBalancer繼承AbstractLoadBalancer

有代碼可以知道new了一個輪詢的策略對象,默認使用輪詢的策略做負載均衡

?

當然我們還可以看本地maven倉庫的Ribbon源碼

但是Ribbon還提供了其他負載均衡的算法,當我們程序顯式的聲明了其他負載均衡的算法,默認就不會生效,假如我們這里顯式的聲明隨機的負載均衡的算法

下面我們將消費者端的負載均衡策略,重新定義隨機策略下不使用默認:

我們再次啟動所有的微服務,啟動所有的服務參考:https://blog.csdn.net/ywl470812087/article/details/102638054

我們測試下是不是能夠隨機

?

?

?

通過訪問多次可以發(fā)現(xiàn)沒有規(guī)律也沒有輪詢,實現(xiàn)了隨機

其余的6種負載均衡策略都是可以這樣實現(xiàn)的,比如RetryRule重試策略等等

總結

以上是生活随笔為你收集整理的SpringCloud Ribbon实战以及Ribbon的源码浅析(四)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。