I want to achieve the following using spring-integration
: having a singleton open socket that constantly receives and writes data, asyncrhon!
This means I have to open a socket that constantly reads from the single socket, dispatches each message for async processing, and return the responses over the socket also async.
How can I achieve that asynchron pattern?
Especially: how can I use Serializer/Deserializer
? As far as I understood, a serializer is only invoked on a new socket connection, so in my case only once at start of the first message?
@Configuration
public class SocketConfig {
@Bean
public TcpConnectionFactoryFactoryBean tcpFactory(MyConverter converter) {
TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean();
fact.setType("server");
fact.setPort(PORT);
fact.setUsingNio(true); //should I use true or false?
fact.setSingleUse(false); //keep socket constantly open
fact.setSerializer(converter);
fact.setDeserializer(converter);
return fact;
}
@Bean
public TcpInboundGateway serverGateway(
@Qualifier("tcpFactory") TcpConnectionFactoryFactoryBean factory,
@Qualifier("serverChannel") MessageChannel serverChannel) throws Exception {
TcpInboundGateway g = new TcpInboundGateway();
g.setConnectionFactory(factory.getObject());
g.setRequestChannel(serverChannel);
return g;
}
}
@MessageEndpoint
public class SocketEndpoint {
@ServiceActivator(inputChannel = "serverChannel")
public Object run(Object obj) {
}
}
@Service
public class MyConverter implements Serializer<Object>, Deserializer<Object> {
//read from socket
@Override
public Object deserialize(InputStream inputStream) {
}
//send back to socket
@Override
public void serialize(Object message, OutputStream outputStream) {
}
}
A gateway is used for individual request/response pairs.
If you need to send multiple responses for a single request, you must use collaborating channel adapters as described in the documentation.
Collaborating adapters can also be used (server-side or client-side) for totally asynchronous communication (rather than with request/reply semantics).
On the server side, care must be taken to populate the ip_connectionId header because it is used to correlate the message to a connection. Messages that originate at the inbound adapter will automatically have the header set. If you wish to construct other messages to send, you will need to set the header. The header value can be captured from an incoming message.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments