核心實現是使用CountDownLatch來實現的,先取集群節點總數一半以上數量的CountDownLatch
再發送請求調用其他節點,在這個過程中對于正常響應的節點進行latch.countDown();
最后再統計數量是否為0再決定是否拋異常
// 請求參數final String content = json.toString();// 這里再去通知其他節點,// peers就是各個集群節點,peers.majorityCount() 取peers.size() / 2 + 1 個數的CountDownLatchfinal CountDownLatch latch = new CountDownLatch(peers.majorityCount());// 遍歷除了自己之外的節點for (final String server : peers.allServersIncludeMyself()) {if (isLeader(server)) {latch.countDown();continue;}// 調用各個節點 發送請求final String url = buildUrl(server, API_ON_PUB);HttpClient.asyncHttpPostLarge(url, Arrays.asList("key", key), content, new Callback<String>() {@Overridepublic void onReceive(RestResult<String> result) {if (!result.ok()) {Loggers.RAFT.warn("[RAFT] failed to publish data to peer, datumId={}, peer={}, http code={}",datum.key, server, result.getCode());return;}latch.countDown();}@Overridepublic void onError(Throwable throwable) {Loggers.RAFT.error("[RAFT] failed to publish data to peer", throwable);}@Overridepublic void onCancel() {}});}if (!latch.await(UtilsAndCommons.RAFT_PUBLISH_TIMEOUT, TimeUnit.MILLISECONDS)) {// only majority servers return success can we consider this update successLoggers.RAFT.error("data publish failed, caused failed to notify majority, key={}", key);throw new IllegalStateException("data publish failed, caused failed to notify majority, key=" + key);}