測試連線
在某些情況下,當首次開啟連線時,傳送某種健康檢查請求可能很有用。其中一種情況可能是使用 TCP Failover Client Connection Factory,以便在選定的伺服器允許開啟連線但報告其不健康時,我們可以進行容錯移轉。
為了支援此功能,請將 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 Failover Client Connection Factory 一起使用時,這會觸發嘗試下一個伺服器。
只有來自伺服器的第一個回覆會傳送到測試接聽器。 |
在以下範例中,如果伺服器在我們傳送 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();
});