这篇文章主要介绍Nginx轮询算法底层如何实现,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
<强>轮询算法简介强>
在工作中很多人都使用到了Nginx,对Nginx得配置也是烂熟于心,今天我主要想介绍一下Nginx轮询算法得几种底层实现方式。
<强>简单轮询算法强>
这种算法比较简单,举个例子就是你有三台服务器
第一台服务器192.168.1.1第二台服务器192.168.1.2第三台服务器192.168.1.3
第一个请求过来之后默认访问第一台,第二个请求过来访问第二台,第三次请求过来访问第三台,第四次请求过来访问第一台,以此类推。以下是我代码实现简单得算法:
public class SimplePolling { ,/* * ,,*,关键是ip ,,*/public 才能;static  List & lt; String>, ipService =, new LinkedList & lt;在(); static {才能 ,,,ipService.add (“192.168.1.1"); ,,,ipService.add (“192.168.1.2"); ,,,ipService.add (“192.168.1.3"); ,,} public 才能static int  pos =, 0; public 才能static String  getIp () { ,,,如果(pos 祝辞=,ipService.size ()) { ,,,,,//防止索引越界 ,,,,,pos =, 0; ,,,} ,,,String ip =, ipService.get (pos); ,,,pos + +; ,,,return 知识产权; ,,} public 才能;static  void main (String [], args), { ,,,for (int 小姐:=,0;,小姐:& lt;, 4,,我+ +),{ ,,,,,System.out.println (getIp ()); ,,,} ,,} }
模拟执行4次执行结果是
public class WeightPolling { ,/* * ,,*,关键是ip,价值是权重 ,,*/public 才能;static  Map<字符串,,Integer>, ipService =, new LinkedHashMap<在(); static {才能 ,,,ipService.put (“192.168.1.1",, 5); ,,,ipService.put (“192.168.1.2",, 1); ,,,ipService.put (“192.168.1.3",, 1); ,,} public 才能static int  requestId =, 0; public 才能static int  getAndIncrement (), { ,,,return requestId + +; ,,} public 才能static String  getIp () { ,,,//获取总的权重 ,,,int totalWeight =0; ,,,for (Integer value : ipService.values ()), { ,,,,,totalWeight +=,价值; ,,,} ,,,//获取当前轮询的值 ,,,int andIncrement =, getAndIncrement (); ,,,int pos =, andIncrement %, totalWeight; ,,,for (String ip : ipService.keySet ()), { ,,,,,如果(pos & lt;, ipService.get (ip)) { ,,,,,,,return 知识产权; ,,,,,} ,,,,,pos -=, ipService.get (ip); ,,,} ,,,return 零; ,,} public 才能;static  void main (String [], args), { ,,,for (int 小姐:=,0;,小姐:& lt;, 7;,我+ +),{ ,,,,,System.out.println (getIp ()); ,,,} ,,} null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null