如需使用最新稳定版本,请使用 Spring Integration 7.0.4spring-doc.cadn.net.cn

测试连接

在某些场景中,当连接首次打开时发送某种健康检查请求可能很有用。 一种这样的场景可能是使用 TCP 故障转移客户端连接工厂,以便如果选定的服务器允许建立连接但报告其不健康时,我们可以进行故障转移。spring-doc.cadn.net.cn

为了支持此功能,请向客户端连接工厂添加一个 connectionTestspring-doc.cadn.net.cn

/**
 * 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-doc.cadn.net.cn

只有服务器的第一条回复会发送到测试监听器。

在以下示例中,如果我们发送 PING,服务器回复 PONG 时,则认为服务器是健康的。spring-doc.cadn.net.cn

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