2016-01-21 94 views
1

我已經配置TcpInboundGateway接收來自客戶端的請求,我的配置如下。因此,根據下面的配置,每個客戶端請求都會被迴應,但是我想要的是響應應該只在某些條件爲真時發回,而不是每次都需要在配置中進行哪些更改?春季集成TcpInboundGateway發送條件回覆

@SpringBootApplication 
@IntegrationComponentScan 
public class SpringIntegrationApplication extends SpringBootServletInitializer{ 


    public static void main(String[] args) throws IOException { 
     ConfigurableApplicationContext ctx = SpringApplication.run(SpringIntegrationApplication.class, args);  
     System.in.read(); 
     ctx.close(); 
    } 


    @Override 
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
     return application.sources(SpringIntegrationApplication.class); 
    } 

    private static Class<SpringIntegrationApplication> applicationClass = SpringIntegrationApplication.class; 


    @Bean 
    TcpNetServerConnectionFactory cf(){ 
     TcpNetServerConnectionFactory connectionFactory=new TcpNetServerConnectionFactory(8765); 

     return connectionFactory; 
    } 

    @Bean 
    TcpInboundGateway tcpGate(){ 

     TcpInboundGateway gateway=new TcpInboundGateway(); 
     gateway.setConnectionFactory(cf()); 
     gateway.setRequestChannel(requestChannel()); 
     return gateway; 
    } 

    @Bean 
    public MessageChannel requestChannel(){ 

     return new DirectChannel(); 
    } 


    @MessageEndpoint 
    public class Echo { 

    @ServiceActivator(inputChannel="requestChannel") 
    public byte[] echo(byte[] in,@SuppressWarnings("deprecation") @Header("ip_address") String ip){ 

     byte[] rawbytes = gosDataSerivce.byteArrayToHex(in,ip);//Process bytes and returns result 

     return rawbytes;  

    } 
    } 

} 

回答

2

不知道哪裏是你的問題,但你可以簡單地從你的echo()返回null。在這種情況下,ServiceActivatingHandler不在乎並停止它的工作。僅僅是因爲requiresReply = false

從對方TcpInboundGateway不關心null,太:

Message<?> reply = this.sendAndReceiveMessage(message); 
if (reply == null) { 
    if (logger.isDebugEnabled()) { 
     logger.debug("null reply received for " + message + " nothing to send"); 
    } 
    return false; 
} 

這是可能的,因爲replyTimeout選項爲MessagingTemplate的背景。默認情況下它是1 sec。在那之後sendAndReceiveMessage()只是返回給調用者null

您可以在TcpInboundGateway上調整此選項。

+1

如果您沒有異步切換,則可以安全地將應答超時設置爲0 - 在線程返回到網關之前,時鐘不會啓動。您還可以使用[協作通道適配器](http://docs.spring.io/spring-integration/reference/html/ip.html#_collaborating_outbound_and_inbound_channel_adapters)代替任意消息傳遞的網關。 –

+0

我的用例是請求/答覆,非阻塞,並應具有多線程支持,可以使用協作通道適配器 – MasterCode