當前位置:
首頁 > 知識 > 負載均衡zookpeer之輪詢演算法

負載均衡zookpeer之輪詢演算法

1 Ngix 和 dubbo的負載均衡的區別?

Ngix負責前端的負載均衡,zookeeper負責後台的dubbo的rpc的集群的負載均衡

2 代碼實現

監聽者

  1. import java.io.IOException;
  2. import org.apache.log4j.Logger;
  3. import org.apache.zookeeper.CreateMode;
  4. import org.apache.zookeeper.KeeperException;
  5. import org.apache.zookeeper.WatchedEvent;
  6. import org.apache.zookeeper.Watcher;
  7. import org.apache.zookeeper.ZooDefs.Ids;
  8. import org.apache.zookeeper.ZooKeeper;
  9. import org.apache.zookeeper.data.Stat;
  10. public class WatchMore
  11. {
  12. /**
  13. * Logger for this class
  14. */
  15. private static final Logger logger = Logger.getLogger(WatchMore.class);
  16. // 定義常量
  17. private static final String CONNECTSTRING = "192.168.10.167:2181";
  18. private static final int SESSION_TIMEOUT = 50 * 1000;
  19. private static final String PATH = "/atguigu";
  20. // 定義實例變數
  21. private ZooKeeper zk = null;
  22. private String oldValue = "";
  23. public ZooKeeper startZK() throws IOException
  24. {
  25. return new ZooKeeper(CONNECTSTRING, SESSION_TIMEOUT, new Watcher() {
  26. @Override
  27. public void process(WatchedEvent event)
  28. {
  29. }
  30. });
  31. }
  32. public void createZNode(String nodePath, String nodeValue) throws KeeperException, InterruptedException
  33. {
  34. zk.create(nodePath, nodeValue.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
  35. }
  36. public String getZNode(String nodePath) throws KeeperException, InterruptedException
  37. {
  38. String result = "";
  39. byte[] byteArray = zk.getData(nodePath, new Watcher() {
  40. @Override
  41. public void process(WatchedEvent event)
  42. {
  43. try {
  44. triggerValue(nodePath);
  45. }
  46. catch (KeeperException | InterruptedException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }, new Stat());
  51. result = new String(byteArray);
  52. oldValue = result;
  53. return result;
  54. }
  55. public boolean triggerValue(String nodePath) throws KeeperException, InterruptedException
  56. {
  57. String result = "";
  58. byte[] byteArray = zk.getData(nodePath, new Watcher() {
  59. @Override
  60. public void process(WatchedEvent event)
  61. {
  62. try {
  63. triggerValue(nodePath);
  64. }
  65. catch (KeeperException | InterruptedException e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }, new Stat());
  70. result = new String(byteArray);
  71. String newValue = result;
  72. if (oldValue.equals(newValue)) {
  73. logger.info("**************no change****************");
  74. return false;
  75. }
  76. else {
  77. logger.info("**************oldValue:" + oldValue + " newValue: " + newValue);
  78. oldValue = newValue;
  79. return true;
  80. }
  81. }
  82. public static void main(String[] args) throws IOException, KeeperException, InterruptedException
  83. {
  84. WatchMore myWatch = new WatchMore();
  85. // 1 獲得zk實例
  86. myWatch.setZk(myWatch.startZK());
  87. if (myWatch.getZk().exists(PATH, false) == null)
  88. {
  89. String initValue = "AAA";
  90. myWatch.createZNode(PATH, initValue);
  91. logger.info("***************main: " + myWatch.getZNode(PATH));
  92. Thread.sleep(Long.MAX_VALUE);
  93. }else {
  94. logger.info("***************have node*******");
  95. }
  96. }
  97. // setter------getter
  98. public ZooKeeper getZk()
  99. {
  100. return zk;
  101. }
  102. public void setZk(ZooKeeper zk)
  103. {
  104. this.zk = zk;
  105. }
  106. public String getOldValue()
  107. {
  108. return oldValue;
  109. }
  110. public void setOldValue(String oldValue)
  111. {
  112. this.oldValue = oldValue;
  113. }
  114. }

3 實現負載均衡的服務

  1. import java.io.IOException;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.apache.log4j.Logger;
  5. import org.apache.zookeeper.KeeperException;
  6. import org.apache.zookeeper.WatchedEvent;
  7. import org.apache.zookeeper.Watcher;
  8. import org.apache.zookeeper.ZooKeeper;
  9. import org.apache.zookeeper.data.Stat;
  10. import com.atguigu.zk.watch.WatchMore;
  11. public class BalanceTest
  12. {
  13. /**
  14. * Logger for this class
  15. */
  16. private static final Logger logger = Logger.getLogger(WatchMore.class);
  17. // 定義常量
  18. private static final String CONNECTSTRING = "192.168.31.167:2181";
  19. private static final int SESSION_TIMEOUT = 50 * 1000;
  20. private static final String PATH = "/atcunzi";
  21. private static final String SUB_PREFIX = "sub";
  22. // 定義實例變數
  23. private ZooKeeper zk = null;
  24. private List<String> serviceLists = new ArrayList<String>(); // sub1,.....sub5 // 用來收集可用服務的
  25. private int subCount = 5; // 可用服務個數
  26. private int currentServiceNum = 0; // 當前請求序號
  27. // 初始化zookeepr,並獲取服務的集合

  28. public ZooKeeper startZK() throws IOException
  29. {
  30. return new ZooKeeper(CONNECTSTRING, SESSION_TIMEOUT,new Watcher() {
  31. @Override
  32. public void process(WatchedEvent event)
  33. {
  34. try
  35. {
  36. serviceLists = zk.getChildren(PATH,true);
  37. }catch (KeeperException | InterruptedException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. });
  42. }
  43. // 處理輪詢演算法邏輯 重要的是怎麼能讓服務 輪詢
  44. public String dealRquest() throws KeeperException, InterruptedException
  45. {
  46. currentServiceNum = currentServiceNum + 1;
  47. for (int i = currentServiceNum; i <=subCount; i++)
  48. {
  49. if(serviceLists.contains(SUB_PREFIX+currentServiceNum))
  50. {
  51. return new String(zk.getData(PATH+"/"+SUB_PREFIX+currentServiceNum,false,new Stat()));
  52. }else{
  53. currentServiceNum = currentServiceNum + 1;
  54. }
  55. }
  56. //重要的是怎麼能讓服務 輪詢 1 3 5 currentServiceNum = 6
  57. for (int i = 1; i <=subCount; i++)
  58. {
  59. if(serviceLists.contains(SUB_PREFIX+i))
  60. {
  61. currentServiceNum = i;
  62. return new String(zk.getData(PATH+"/"+SUB_PREFIX+currentServiceNum,false,new Stat()));
  63. }
  64. }
  65. return "no subNode~~~~~";
  66. }
  67. public static void main(String[] args) throws IOException, InterruptedException
  68. {
  69. BalanceTest test = new BalanceTest();
  70. test.setZk(test.startZK());
  71. Thread.sleep(3000);
  72. String result = null;
  73. for (int i = 1; i <=15; i++)
  74. {
  75. try
  76. {
  77. result = test.dealRquest();
  78. logger.info("*********customerID: "+i+" currentWindows:"+test.currentServiceNum+" "+result);
  79. Thread.sleep(2000);
  80. }
  81. catch (KeeperException | InterruptedException e) {
  82. e.printStackTrace();
  83. }
  84. }
  85. }
  86. ///----setter=-=getter
  87. public ZooKeeper getZk()
  88. {
  89. return zk;
  90. }
  91. public void setZk(ZooKeeper zk)
  92. {
  93. this.zk = zk;
  94. }
  95. }

4 總結

負載均衡可以看成一個銀行,請求看成是顧客,後台服務看成是銀行櫃檯,大堂經理可以看成zookeeper

服務啟動的時候,需要先準備各個銀行櫃檯都準備好,當顧客來到時候,可以 通過大堂經理的指引,去到相應的櫃檯進行櫃檯處理。

難點:當一個櫃檯暫停服務時候,大唐經理怎麼知道的,並且怎麼分發處理,並且服務怎麼輪詢的?

5 maven配置

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.atguigu.zk1014</groupId>
  5. <artifactId>zk1014</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>jar</packaging>
  8. <name>zk1014</name>
  9. <url>http://maven.apache.org</url>
  10. <properties>
  11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  12. </properties>
  13. <dependencies>
  14. <!-- https://mvnrepository.com/artifact/com.101tec/zkclient -->
  15. <dependency>
  16. <groupId>com.101tec</groupId>
  17. <artifactId>zkclient</artifactId>
  18. <version>0.10</version>
  19. </dependency>
  20. <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
  21. <dependency>
  22. <groupId>org.apache.zookeeper</groupId>
  23. <artifactId>zookeeper</artifactId>
  24. <version>3.4.9</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>log4j</groupId>
  28. <artifactId>log4j</artifactId>
  29. <version>1.2.17</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>junit</groupId>
  33. <artifactId>junit</artifactId>
  34. <version>4.9</version>
  35. <scope>test</scope>
  36. </dependency>
  37. </dependencies>
  38. </project>

負載均衡zookpeer之輪詢演算法

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

SQL Server服務遠程過程調用失敗解決
HTTP協議又冷又實用的技能大全

TAG:程序員小新人學習 |