此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Integration 6.5.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 故障转移客户端连接工厂一起使用时,这会触发尝试下一台服务器。
只有来自服务器的第一个回复才会发送给测试侦听器。 |
在以下示例中,如果服务器回复,则服务器被视为正常PONG
当我们发送PING
.
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();
});