接続をテスト

一部のシナリオでは、接続が最初に開かれたときに、ある種のヘルスチェックリクエストを送信すると便利な場合があります。そのようなシナリオの 1 つは、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();
});