Kevin Bos
Kevin Bos

Reputation: 193

Spring integration multiple tcp connections to different servers

Is it possible to set up a dynamic TCP client that can connect to multiple TCP servers at once? I'm using spring integration with dsl configuration. I've read some other questions about this topic but can't figure out a way to make it work.

The configuration I use to set up a single connection below:

@Configuration
public class TcpAsyncConfig {

MessageHandler handler = new MessageHandler();

@Bean
public AbstractClientConnectionFactory client1() {
    return Tcp.netClient("localhost", 6050)
            .leaveOpen(true)
            .soKeepAlive(true)
            .singleUseConnections(true)
            .deserializer(new CustomSerializerDeserializer())
            .get();
}

@Bean
public IntegrationFlow client1Out(AbstractClientConnectionFactory client1) {
    return IntegrationFlows.from(RobotGateways.class)
            .handle(Tcp.outboundAdapter(client1))
            .get();
}

@Bean
public IntegrationFlow client1In(AbstractClientConnectionFactory client1) {
    return IntegrationFlows.from(Tcp.inboundAdapter(client1))
            .transform(Transformers.objectToString())
            .log(msg -> "client1: " + msg.getPayload())
            .handle(handler::handleMessage)
            .get();
}

@Bean
@DependsOn("client1Out")
public RobotGateways robotGateways(RobotGateways gateways){
    return gateways;
}
}

So I want to create a list of connections and use the gateway to send messages on a specific connection.

Upvotes: 0

Views: 788

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121550

One AbstractClientConnectionFactory can really connect only to one TCP server. To make connections to different server you need to have several Tcp.netClient(), respectively.

You then probably need to have several Tcp.outboundAdapter() and Tcp.inboundAdapter() definitions.

In the gateway flow, to determine to which client to send, you need to take a look into a route() where according some gateway call argument you can decide to where to go in your flow.

See docs for more info:

https://docs.spring.io/spring-integration/docs/current/reference/html/dsl.html#java-dsl-routers https://docs.spring.io/spring-integration/docs/current/reference/html/message-routing.html#messaging-routing-chapter

Upvotes: 1

Related Questions