測試連線

在某些場景下,當連線首次開啟時傳送某種健康檢查請求可能會很有用。一種這樣的場景是在使用 TCP 故障轉移客戶端連線工廠 時,以便在選定的伺服器允許連線開啟但報告不健康時能夠進行故障轉移。

為了支援此功能,請向客戶端連線工廠新增 connectionTest

/**
 * Set a {@link Predicate} that will be invoked to test a new connection; return true
 * to accept the connection, false the reject.
 * @param connectionTest the predicate.
 * @since 5.3
 */
public void setConnectionTest(@Nullable Predicate<TcpConnectionSupport> connectionTest) {
    this.connectionTest = connectionTest;
}

為了測試連線,在測試期間向連線附加一個臨時監聽器。如果測試失敗,連線將被關閉並丟擲異常。與 TCP 故障轉移客戶端連線工廠 一起使用時,這會觸發嘗試下一個伺服器。

伺服器的第一個回覆將只發送給測試監聽器。

在以下示例中,如果伺服器在我們傳送 PING 時回覆 PONG,則認為伺服器是健康的。

Message<String> ping = new GenericMessage<>("PING");
byte[] pong = "PONG".getBytes();
clientFactory.setConnectionTest(conn -> {
    CountDownLatch latch = new CountDownLatch(1);
    AtomicBoolean result = new AtomicBoolean();
    conn.registerTestListener(msg -> {
        if (Arrays.equals(pong, (byte[]) msg.getPayload())) {
            result.set(true);
        }
        latch.countDown();
        return false;
    });
    conn.send(ping);
    try {
        latch.await(10, TimeUnit.SECONDS);
    }
    catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return result.get();
});