此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Integration 6.3.1Spring中文文档

此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Integration 6.3.1Spring中文文档

在某些情况下,在首次打开连接时发送某种运行状况检查请求可能很有用。 其中一种情况可能是使用 TCP 故障转移客户端连接工厂时,这样,如果所选服务器允许打开连接但报告连接不正常,我们可以进行故障转移。Spring中文文档

为了支持此功能,请向客户端连接工厂添加一个。connectionTestSpring中文文档

/**
 * 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 故障转移客户端连接工厂一起使用时,这会触发尝试下一个服务器。Spring中文文档

只有来自服务器的第一个回复才会转到测试侦听器。
只有来自服务器的第一个回复才会转到测试侦听器。

在以下示例中,如果服务器在我们发送 .PONGPINGSpring中文文档

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();
});