測試連線
在某些情況下,當連線首次開啟時傳送某種健康檢查請求會很有用。例如,在使用 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();
});