posts - 495,comments - 227,trackbacks - 0
          <2012年7月>
          24252627282930
          1234567
          891011121314
          15161718192021
          22232425262728
          2930311234

          常用鏈接

          留言簿(46)

          隨筆分類(476)

          隨筆檔案(495)

          最新隨筆

          搜索

          •  

          積分與排名

          • 積分 - 1396474
          • 排名 - 16

          最新評論

          閱讀排行榜

          評論排行榜

          http://www.cnblogs.com/phinecos/archive/2012/02/16/2354834.html

          上一篇中介紹了SolrCloud的第一個模塊---構(gòu)建管理solr集群狀態(tài)信息的zookeeper集群。當(dāng)我們在solr服務(wù)器啟動時擁有了這樣一個Zookeeper集群后,顯然我們需要連接到Zookeeper集群的方便手段,在這一篇中我將對Zookeeper客戶端相關(guān)的各個封裝類進(jìn)行分析。

          SolrZkClient類是Solr服務(wù)器用來與Zookeeper集群進(jìn)行通信的接口類,它包含的主要組件有:

            private ConnectionManager connManager;
            private volatile SolrZooKeeper keeper;
            private ZkCmdExecutor zkCmdExecutor = new ZkCmdExecutor();

              其中ConnectionManagerWatcher的實現(xiàn)類,主要負(fù)責(zé)對客戶端與Zookeeper集群之間連接的狀態(tài)變化信息進(jìn)行響應(yīng),關(guān)于Watcher的詳細(xì)介紹,可以參考http://zookeeper.apache.org/doc/trunk/zookeeperProgrammers.html#ch_zkWatches

          SolrZooKeeper類是一個包裝類,沒有實際意義,ZkCmdExecutor類是負(fù)責(zé)在連接失敗的情況下,重試某種操作特定次數(shù),具體的操作是ZkOperation這個抽象類的具體實現(xiàn)子類,其execute方法中包含了具體操作步驟,這些操作包括新建一個Znode節(jié)點,讀取Znode節(jié)點數(shù)據(jù),創(chuàng)建Znode路徑,刪除Znode節(jié)點等Zookeeper操作。

          首先來看它的構(gòu)造函數(shù),先創(chuàng)建ConnectionManager對象來響應(yīng)兩端之間的狀態(tài)變化信息,然后ZkClientConnectionStrategy類是一個連接策略抽象類,它包含連接和重連兩種策略,并且采用模板方法模式,具體的實現(xiàn)是通過靜態(tài)累不類ZkUpdate來實現(xiàn)的,DefaultConnectionStrategy是它的一個實現(xiàn)子類,它覆寫了connectreconnect兩個連接策略方法。

          復(fù)制代碼
            public SolrZkClient(String zkServerAddress, int zkClientTimeout,
                ZkClientConnectionStrategy strat, final OnReconnect onReconnect, int clientConnectTimeout) throws InterruptedException,
                TimeoutException, IOException {
              connManager = new ConnectionManager("ZooKeeperConnection Watcher:"
                  + zkServerAddress, this, zkServerAddress, zkClientTimeout, strat, onReconnect);
              strat.connect(zkServerAddress, zkClientTimeout, connManager,
                  new ZkUpdate() {
                    @Override
                    public void update(SolrZooKeeper zooKeeper) {
                      SolrZooKeeper oldKeeper = keeper;
                      keeper = zooKeeper;
                      if (oldKeeper != null) {
                        try {
                          oldKeeper.close();
                        } catch (InterruptedException e) {
                          // Restore the interrupted status
                          Thread.currentThread().interrupt();
                          log.error("", e);
                          throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
                              "", e);
                        }
                      }
                    }
                  });
              connManager.waitForConnected(clientConnectTimeout);
              numOpens.incrementAndGet();
            }
          復(fù)制代碼

          值得注意的是,構(gòu)造函數(shù)中生成的ZkUpdate匿名類對象,它的update方法會被調(diào)用,

          在這個方法里,會首先將已有的老的SolrZooKeeperg關(guān)閉掉,然后放置上一個新的SolrZooKeeper。做好這些準(zhǔn)備工作以后,就會去連接Zookeeper服務(wù)器集群,

          connManager.waitForConnected(clientConnectTimeout);//連接zk服務(wù)器集群,默認(rèn)30秒超時時間

          其實具體的連接動作是new SolrZooKeeper(serverAddress, timeout, watcher)引發(fā)的,上面那句代碼只是在等待指定時間,看是否已經(jīng)連接上。

          如果連接Zookeeper服務(wù)器集群成功,那么就可以進(jìn)行Zookeeper的常規(guī)操作了:

          1) 是否已經(jīng)連接

            public boolean isConnected() {
              return keeper != null && keeper.getState() == ZooKeeper.States.CONNECTED;
            }

          2) 是否存在某個路徑的Znode

          復(fù)制代碼
            public Stat exists(final String path, final Watcher watcher, boolean retryOnConnLoss) throws KeeperException, InterruptedException {
              if (retryOnConnLoss) {
                return zkCmdExecutor.retryOperation(new ZkOperation() {
                  @Override
                  public Stat execute() throws KeeperException, InterruptedException {
                    return keeper.exists(path, watcher);
                  }
                });
              } else {
                return keeper.exists(path, watcher);
              }
            }
          復(fù)制代碼

          3) 創(chuàng)建一個Znode節(jié)點

          復(fù)制代碼
            public String create(final String path, final byte data[], final List<ACL> acl, final CreateMode createMode, boolean retryOnConnLoss) throws KeeperException, InterruptedException {
              if (retryOnConnLoss) {
                return zkCmdExecutor.retryOperation(new ZkOperation() {
                  @Override
                  public String execute() throws KeeperException, InterruptedException {
                    return keeper.create(path, data, acl, createMode);
                  }
                });
              } else {
                return keeper.create(path, data, acl, createMode);
              }
            }
          復(fù)制代碼

          4) 獲取指定路徑下的孩子Znode節(jié)點

          復(fù)制代碼
            public List<String> getChildren(final String path, final Watcher watcher, boolean retryOnConnLoss) throws KeeperException, InterruptedException {
              if (retryOnConnLoss) {
                return zkCmdExecutor.retryOperation(new ZkOperation() {
                  @Override
                  public List<String> execute() throws KeeperException, InterruptedException {
                    return keeper.getChildren(path, watcher);
                  }
                });
              } else {
                return keeper.getChildren(path, watcher);
              }
            }
          復(fù)制代碼

          5) 獲取指定Znode上附加的數(shù)據(jù)

          復(fù)制代碼
            public byte[] getData(final String path, final Watcher watcher, final Stat stat, boolean retryOnConnLoss) throws KeeperException, InterruptedException {
              if (retryOnConnLoss) {
                return zkCmdExecutor.retryOperation(new ZkOperation() {
                  @Override
                  public byte[] execute() throws KeeperException, InterruptedException {
                    return keeper.getData(path, watcher, stat);
                  }
                });
              } else {
                return keeper.getData(path, watcher, stat);
              }
            }
          復(fù)制代碼

          6) 在指定Znode上設(shè)置數(shù)據(jù)

          復(fù)制代碼
            public Stat setData(final String path, final byte data[], final int version, boolean retryOnConnLoss) throws KeeperException, InterruptedException {
              if (retryOnConnLoss) {
                return zkCmdExecutor.retryOperation(new ZkOperation() {
                  @Override
                  public Stat execute() throws KeeperException, InterruptedException {
                    return keeper.setData(path, data, version);
                  }
                });
              } else {
                return keeper.setData(path, data, version);
              }
            }
          復(fù)制代碼

          7) 創(chuàng)建路徑

          復(fù)制代碼
            public void makePath(String path, byte[] data, CreateMode createMode, Watcher watcher, boolean failOnExists, boolean retryOnConnLoss) throws KeeperException, InterruptedException {
              if (log.isInfoEnabled()) {
                log.info("makePath: " + path);
              }
              boolean retry = true;
              
              if (path.startsWith("/")) {
                path = path.substring(1, path.length());
              }
              String[] paths = path.split("/");
              StringBuilder sbPath = new StringBuilder();
              for (int i = 0; i < paths.length; i++) {
                byte[] bytes = null;
                String pathPiece = paths[i];
                sbPath.append("/" + pathPiece);
                final String currentPath = sbPath.toString();
                Object exists = exists(currentPath, watcher, retryOnConnLoss);
                if (exists == null || ((i == paths.length -1) && failOnExists)) {
                  CreateMode mode = CreateMode.PERSISTENT;
                  if (i == paths.length - 1) {
                    mode = createMode;
                    bytes = data;
                    if (!retryOnConnLoss) retry = false;
                  }
                  try {
                    if (retry) {
                      final CreateMode finalMode = mode;
                      final byte[] finalBytes = bytes;
                      zkCmdExecutor.retryOperation(new ZkOperation() {
                        @Override
                        public Object execute() throws KeeperException, InterruptedException {
                          keeper.create(currentPath, finalBytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, finalMode);
                          return null;
                        }
                      });
                    } else {
                      keeper.create(currentPath, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, mode);
                    }
                  } catch (NodeExistsException e) {
                    
                    if (!failOnExists) {
                      // TODO: version ? for now, don't worry about race
                      setData(currentPath, data, -1, retryOnConnLoss);
                      // set new watch
                      exists(currentPath, watcher, retryOnConnLoss);
                      return;
                    }
                    
                    // ignore unless it's the last node in the path
                    if (i == paths.length - 1) {
                      throw e;
                    }
                  }
                  if(i == paths.length -1) {
                    // set new watch
                    exists(currentPath, watcher, retryOnConnLoss);
                  }
                } else if (i == paths.length - 1) {
                  // TODO: version ? for now, don't worry about race
                  setData(currentPath, data, -1, retryOnConnLoss);
                  // set new watch
                  exists(currentPath, watcher, retryOnConnLoss);
                }
              }
            }
          復(fù)制代碼

          8) 刪除指定Znode

          復(fù)制代碼
            public void delete(final String path, final int version, boolean retryOnConnLoss) throws InterruptedException, KeeperException {
              if (retryOnConnLoss) {
                zkCmdExecutor.retryOperation(new ZkOperation() {
                  @Override
                  public Stat execute() throws KeeperException, InterruptedException {
                    keeper.delete(path, version);
                    return null;
                  }
                });
              } else {
                keeper.delete(path, version);
              }
            }
          復(fù)制代碼

                   我們再回過頭來看看ConnectionManager類是如何響應(yīng)兩端的連接狀態(tài)信息的變化的,它最重要的方法是process方法,當(dāng)它被觸發(fā)回調(diào)時,會從WatchedEvent參數(shù)中得到事件的各種狀態(tài)信息,比如連接成功,會話過期(此時需要進(jìn)行重連),連接斷開等。

          復(fù)制代碼
            public synchronized void process(WatchedEvent event) {
              if (log.isInfoEnabled()) {
                log.info("Watcher " + this + " name:" + name + " got event " + event + " path:" + event.getPath() + " type:" + event.getType());
              }

              state = event.getState();
              if (state == KeeperState.SyncConnected) {
                connected = true;
                clientConnected.countDown();
              } else if (state == KeeperState.Expired) {
                connected = false;
                log.info("Attempting to reconnect to recover relationship with ZooKeeper...");
                //嘗試重新連接zk服務(wù)器
                try {
                  connectionStrategy.reconnect(zkServerAddress, zkClientTimeout, this,
                      new ZkClientConnectionStrategy.ZkUpdate() {
                        @Override
                        public void update(SolrZooKeeper keeper) throws InterruptedException, TimeoutException, IOException {
                          synchronized (connectionStrategy) {
                            waitForConnected(SolrZkClient.DEFAULT_CLIENT_CONNECT_TIMEOUT);
                            client.updateKeeper(keeper);
                            if (onReconnect != null) {
                              onReconnect.command();
                            }
                            synchronized (ConnectionManager.this) {
                              ConnectionManager.this.connected = true;
                            }
                          }
                          
                        }
                      });
                } catch (Exception e) {
                  SolrException.log(log, "", e);
                }
                log.info("Connected:" + connected);
              } else if (state == KeeperState.Disconnected) {
                connected = false;
              } else {
                connected = false;
              }
              notifyAll();
            }
          復(fù)制代碼

           

           

          posted on 2012-07-04 18:41 SIMONE 閱讀(626) 評論(0)  編輯  收藏 所屬分類: solr
          主站蜘蛛池模板: 米林县| 莆田市| 安西县| 万盛区| 滕州市| 镇沅| 湖南省| 静安区| 砀山县| 兴山县| 盐池县| 晋江市| 日照市| 和硕县| 南开区| 寿阳县| 潞城市| 吴忠市| 永福县| 汝城县| 双鸭山市| 黄浦区| 定西市| 阳朔县| 鸡西市| 白河县| 邵武市| 博乐市| 屯昌县| 元氏县| 富民县| 铁力市| 上林县| 泾源县| 桐城市| 东阿县| 元阳县| 青河县| 望都县| 赤城县| 沙河市|