问题
I am using @MessagingGateway to send data to to server. I configured a AbstractClientConnectionFactory and a @ServiceActivator for my outbound gateway.
In order to send data to my server, I need to send a handshake message when the connection is initiated. If the response from server is the response that I expect for the handshake, then I send meaningful data. My initial solution is
if (gateway.handshake(HANDSHAKE).equals(HANDSHAKE_RESPONSE))
gateway.sendData(data);
This is not so good when i am scaling up because I have doubled my calls over tcp as I only need to send send handshake on connection initiation and not every time. Also, I plan on keeping the connection alive.
So on connection initiation, how can I have this custom handshake implemented?
@Bean
public AbstractClientConnectionFactory clientCF() {
TcpNetClientConnectionFactory tcpNetClientConnectionFactory = new TcpNetClientConnectionFactory(host, port);
tcpNetClientConnectionFactory.setSerializer(new serializerDeserializer());
tcpNetClientConnectionFactory.setDeserializer(new serializerDeserializer());
tcpNetClientConnectionFactory.setSoKeepAlive(true);
tcpNetClientConnectionFactory.setSoTimeout(soTimeout);
return tcpNetClientConnectionFactory;
}
@Bean
@ServiceActivator(inputChannel = "toTcp")
public MessageHandler tcpOutGate(AbstractClientConnectionFactory connectionFactory) {
TcpOutboundGateway gate = new TcpOutboundGateway();
gate.setConnectionFactory(connectionFactory);
return gate;
}
@Bean
public MessageChannel fromTcp() {
return new DirectChannel();
}
回答1:
See Connection Interceptors.
Connection factories can be configured with a reference to a TcpConnectionInterceptorFactoryChain. Interceptors can be used to add behavior to connections, such as negotiation, security, and other setup. No interceptors are currently provided by the framework but, for an example, see the InterceptedSharedConnectionTests in the source repository.
The HelloWorldInterceptor used in the test case works as follows:
...
While there are no standard interceptors in the framework, there are test cases that show how to use them for an initial handshake, for example here and here.
The tests are more complex than you need because they test multiple nested interceptors.
The hello world test interceptors send Hello
and expect World!
when the socket is first opened. They implement the handshake for both the client and server side.
来源:https://stackoverflow.com/questions/48632414/spring-integration-tcp-initiate-handshake-with-a-message-before-sending-data