Search code examples
spring-integration

Spring Integration TCP - request/response switch request to the channels


I am doing Spring Integration with Server and Client request/response demo. The request comes with a Byte array which is to be converted to Object. Then the request comes to the input channel, I need to check which class is to be send to the service activator. Then the service activator will send it to the reply channel.

<bean id="javaSerializer"
      class="org.springframework.core.serializer.DefaultSerializer"/>
      
<bean id="javaDeserializer"
      class="org.springframework.core.serializer.DefaultDeserializer"/> 

<!-- single-use="true" : A new message has to wait until the reply to the previous message has been received -->
<int-ip:tcp-connection-factory id="server"
    type="server"
    host="localhost"
    port="10101"
    single-use="true"
    so-timeout="10000"
    serializer="javaSerializer"
    deserializer="javaDeserializer" 
    task-executor="severTaskExecutor"/>
      
<int-ip:tcp-inbound-gateway id="inGateway"
    request-channel="inputChannel"
    reply-channel="replyChannel"
    connection-factory="server"
    reply-timeout="10000"/>
    
<int:channel id="inputChannel"/>

<!-- How to switch the request to the different channel??? -->

<int:channel id="myChannelOne"/>
<int:channel id="myChannelTwo"/>

<int:service-activator 
    input-channel="myChannelOne"
    output-channel="replyChannel"
    ref="myServiceOne"
    method="get" />
    
<int:service-activator 
    input-channel="myChannelTwo"
    output-channel="replyChannel"
    ref="myServiceTwo"
    method="get" />
    
<int:channel id="replyChannel"/>

<bean id="myServiceOne" class="com.my.demo.MyServiceOne"/>
<bean id="myServiceTwo" class="com.my.demo.MyServiceTwo"/>

Solution

  • Use a payload type router https://docs.spring.io/spring-integration/docs/current/reference/html/message-routing.html#router-implementations-payloadtyperouter

    <int:payload-type-router input-channel="routingChannel">
        <int:mapping type="java.lang.String" channel="stringChannel" />
        <int:mapping type="java.lang.Integer" channel="integerChannel" />
    </int:payload-type-router>