xylz,imxylz

          關(guān)注后端架構(gòu)、中間件、分布式和并發(fā)編程

             :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            111 隨筆 :: 10 文章 :: 2680 評(píng)論 :: 0 Trackbacks

          公告

          常用鏈接

          留言簿(149)

          隨筆分類(137)

          隨筆檔案(107)

          文章分類(12)

          文章檔案(12)

          友情鏈接

          搜索

          積分與排名

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          Session連接

          Zookeeper客戶端和服務(wù)端維持一個(gè)長(zhǎng)連接,每隔10s向服務(wù)端發(fā)送一個(gè)心跳,服務(wù)端返回客戶端一個(gè)響應(yīng)。這就是一個(gè)Session連接,擁有全局唯一的session id。Session連接通常是一直有效,如果因?yàn)榫W(wǎng)絡(luò)原因斷開了連接,客戶端會(huì)使用相同的session id進(jìn)行重連。由于服務(wù)端保留了session的各種狀態(tài),尤其是各種瞬時(shí)節(jié)點(diǎn)是否刪除依賴于session是否失效。

          Session失效問題

          通常客戶端主動(dòng)關(guān)閉連接認(rèn)為是一次session失效。另外也有可能因?yàn)槠渌粗颍缇W(wǎng)絡(luò)超時(shí)導(dǎo)致的session失效問題。在服務(wù)端看來(lái),無(wú)法區(qū)分session失效是何種情況,一次一旦發(fā)生session失效,一定時(shí)間后就會(huì)將session持有的所有watcher以及瞬時(shí)節(jié)點(diǎn)刪除。

          而對(duì)于Zookeeper客戶端而言,一旦發(fā)生失效不知道是否該重連,這涉及到watcher和瞬時(shí)節(jié)點(diǎn)問題,因此Zookeeper客戶端認(rèn)為,一旦發(fā)生了seesion失效,那么就認(rèn)為客戶端死掉了。從而所有操作都不能夠進(jìn)行。參考 How should I handle SESSION_EXPIRED?

          解決方案

          對(duì)于只是簡(jiǎn)單查詢服務(wù)的客戶端而言,session失效后只需要重新建立連接即可。而對(duì)于需要處理瞬時(shí)節(jié)點(diǎn)以及各種watcher的服務(wù)來(lái)說(shuō),應(yīng)用程序需要處理session失效或者重連帶來(lái)的副作用。

          下面的邏輯提供了一種簡(jiǎn)單的解決session重連的問題,這是指重新生成新的連接。

          public static org.apache.zookeeper.ZooKeeper getZooKeeper() {
            if (zookeeper == null) {
              synchronized (ZookeeperClient.class) {
                if (zookeeper == null) {
                  latch = new CountDownLatch(1);
                  zookeeper = buildClient();//如果失敗,下次還有成功的機(jī)會(huì)
                  long startTime = System.currentTimeMillis();
                  try {
                     latch.await(30, TimeUnit.SECONDS);
                  } catch (InterruptedException e) {
                     e.printStackTrace();
                  } finally {
                    final SocketAddress remoteAddres = zookeeper.testableRemoteSocketAddress();
                    System.out.println("[SUC-CORE] local host: " + zookeeper.testableLocalSocketAddress());
                    System.out.println("[SUC-CORE] remote host: " + remoteAddres);
                    System.out.println("[SUC-CORE] zookeeper session id: " + zookeeper.getSessionId());
                    final String remoteHost = remoteAddres != null ? ((InetSocketAddress) remoteAddres).getAddress().getHostAddress() : "";
                    System.out.println("[SUC-CORE] init cost: " + (System.currentTimeMillis() - startTime) + "(ms) " + remoteHost);
                    latch = null;
                  }
                }
              }
            }
            return zookeeper;
          }

          上面的代碼只是簡(jiǎn)單的使用一個(gè)Double-Check來(lái)維持Zookeeper客戶端的單實(shí)例。保證總是有機(jī)會(huì)重建客戶端以及只有一個(gè)單例(這是因?yàn)閆ookeeper客戶端是線程安全的)。

          例外上面的例子中繼承了org.apache.zookeeper.ZooKeeper類,以便能夠拿到session對(duì)于的服務(wù)端ip地址以及客戶端地址,方便調(diào)試問題。

          在構(gòu)建客戶端的時(shí)候是需要設(shè)置session超時(shí)的時(shí)間,例如下面的代碼就是30秒。


          private static ZooKeeper buildClient() {
              final String rootPath = getRootPath();
              final String connectString = SystemConfig.getInstance().getString("zookeeper.ips",//
                      "192.168.10.1:2181,192.168.10.2:2181,192.168.10.3:2181,192.168.10.4:2181,192.168.10.5:2181");
              System.out.printf("[SUC-CORE] rootPath: %1s\n", rootPath);
              System.out.printf("[SUC-CORE] connectString:%1s\n", connectString);
              try {
                  return new ZooKeeper(connectString + rootPath, 30000, new SessionWatcher());
              } catch (IOException e) {
                  throw new RuntimeException("init zookeeper fail.", e);
              }
          }

          為了處理連接建立成功以及斷開問題,我們需要一個(gè)Watcher來(lái)處理此問題。

          static class SessionWatcherimplements Watcher {

              public void process(WatchedEvent event) {
                  if (event.getState() == KeeperState.SyncConnected) {
                      if (latch != null) {
                          latch.countDown();
                      }
                  } else if (event.getState() == KeeperState.Expired) {
                      System.out.println("[SUC-CORE] session expired. now rebuilding");

                      //session expired, may be never happending.
                      
          //close old client and rebuild new client
                      close();

                      getZooKeeper();
                  }
              }
          }


          一旦檢測(cè)到session失效了(Expired),那么久銷毀已經(jīng)建立的客戶端實(shí)例,重新生成一個(gè)客戶端實(shí)例。

          /**
           * 關(guān)閉zookeeper連接,釋放資源
           
          */
          public static void close() {
              System.out.println("[SUC-CORE] close");
              if (zookeeper != null) {
                  try {
                      zookeeper.close();
                      zookeeper = null;
                  } catch (InterruptedException e) {
                      //ignore exception
                  }
              }
          }

          這是一種簡(jiǎn)單的處理Session expired問題的方法,顯然這不會(huì)處理瞬時(shí)節(jié)點(diǎn)的問題,因此如果有相關(guān)的需求,業(yè)務(wù)系統(tǒng)(應(yīng)用程序)需要自己修復(fù)問題。

          測(cè)試方案

          根據(jù)Is there an easy way to expire a session for testing? 提供的測(cè)試方法,寫一個(gè)簡(jiǎn)單的例子試驗(yàn)下。

          public static void main(String[] args) throws Exception {
            ZooKeeper zk = ZookeeperClient.getZooKeeper();
            long sessionId = zk.getSessionId();
            //
            final String rootPath = ZookeeperClient.getRootPath();
            final String connectString = SystemConfig.getInstance().getString("zookeeper.ips",//
                    "192.168.10.1:2181,192.168.10.2:2181,192.168.10.3:2181,192.168.10.4:2181,192.168.10.5:2181");
            // close the old connection
            new ZooKeeper(connectString + rootPath, 30000, null, sessionId, null).close();
            Thread.sleep(10000L);
            //

            
          // rebuild a new session
            long newSessionid = ZookeeperClient.getZooKeeper().getSessionId();

            // check the new session
            String status = newSessionid != sessionId ? "OK" : "FAIL";
            System.out.println(format("%s --> %s %s", sessionId, newSessionid, status));

            // close the client
            ZookeeperClient.getZooKeeper().close();
          }

          最后能夠自動(dòng)處理session expired的問題。實(shí)驗(yàn)中看到確實(shí)執(zhí)行了session expired的邏輯重新生成了新的session。



          ©2009-2014 IMXYLZ |求賢若渴
          posted on 2011-12-05 13:57 imxylz 閱讀(28637) 評(píng)論(8)  編輯  收藏 所屬分類: J2EE技術(shù)

          評(píng)論

          # re: 處理Zookeeper的session過(guò)期問題 2011-12-06 11:03 TBW
          xiexie !這個(gè)東西我還是要學(xué)的  回復(fù)  更多評(píng)論
            

          # re: 處理Zookeeper的session過(guò)期問題 2011-12-07 17:09 雪地靴
          源碼好復(fù)雜,轉(zhuǎn)載下。  回復(fù)  更多評(píng)論
            

          # re: 處理Zookeeper的session過(guò)期問題 2011-12-15 00:31 Tai
          艷兄永遠(yuǎn)活在我們心中  回復(fù)  更多評(píng)論
            

          # re: 處理Zookeeper的session過(guò)期問題 2012-09-24 16:54 凌波微步
          每隔10s向服務(wù)端發(fā)送一個(gè)心跳
          說(shuō)的不對(duì)!  回復(fù)  更多評(píng)論
            

          # re: 處理Zookeeper的session過(guò)期問題[未登錄] 2014-04-11 09:36 XX
          @凌波微步
          是的,這里不是固定10S。  回復(fù)  更多評(píng)論
            

          # re: 處理Zookeeper的session過(guò)期問題[未登錄] 2014-05-09 16:31 w
          學(xué)習(xí)學(xué)習(xí)  回復(fù)  更多評(píng)論
            

          # re: 處理Zookeeper的session過(guò)期問題 2014-08-07 18:52 iteblog
          寫的不錯(cuò),但是有個(gè)地方錯(cuò)誤:每隔10s向服務(wù)端發(fā)送一個(gè)心跳
          這是不對(duì)的。多久向Zookeeper Server發(fā)送心跳和設(shè)置的Session有關(guān)。  回復(fù)  更多評(píng)論
            

          # re: 處理Zookeeper的session過(guò)期問題 2016-06-17 03:02 codewarrior
          "而對(duì)于Zookeeper客戶端而言,一旦發(fā)生失效不知道是否該重連",這句理解不對(duì)吧,Zookeeper wiki上明確寫了,當(dāng)客戶端斷開后,客戶端無(wú)法得到SESSION_EXPIRED通知,因?yàn)殒溄訑嗔嗽趺窗l(fā)送消息?而自動(dòng)重連是ZK client library自己進(jìn)行的。換言之客戶端是無(wú)法知道自己是否失效的,SESSION_EXPIRED通知只有當(dāng)重連成功后才能收到。  回復(fù)  更多評(píng)論
            


          ©2009-2014 IMXYLZ
          主站蜘蛛池模板: 沾益县| 桦南县| 连云港市| 宣恩县| 阿荣旗| 富蕴县| 安宁市| 山东省| 柯坪县| 永吉县| 增城市| 马公市| 辛集市| 金塔县| 连云港市| 嘉定区| 克东县| 瓦房店市| 化德县| 竹北市| 贡觉县| 旬阳县| 萨迦县| 临朐县| 神池县| 寻甸| 武隆县| 兴山县| 洞头县| 丹巴县| 利川市| 永宁县| 花垣县| 苏州市| 桂阳县| 石屏县| 曲阳县| 宣武区| 榆社县| 旌德县| 鄢陵县|