2017-09-26 120 views
0

我在Spring集成實現了一個簡單的TCP連接工廠:Spring集成頭

@Bean 
@ServiceActivator(inputChannel = "toTcpChannel") 
public TcpSendingMessageHandler tcpOutClient() throws Exception { 
    TcpSendingMessageHandler sender = new TcpSendingMessageHandler(); 
    sender.setConnectionFactory(clientFactory()); 
    sender.setClientMode(false); 
    sender.afterPropertiesSet(); 
    return sender; 
} 

@Bean 
public AbstractClientConnectionFactory clientFactory() { 
    final TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory(tcpHost, tcpPort); 
    factory.setSingleUse(true); 
    return factory; 
} 

@EventListener 
public void handleTcpConnectionOpenEvent(TcpConnectionOpenEvent event) throws Exception {   
LOGGER.info("TCP connection OPEN event: {}", event.getConnectionId()); 
// HERE I would like to have "myCustomID" header here. 
} 

我找得到,我通過網關在生產TcpConnectionOpenEvent提供自定義ID(或類似的通過攔截器)

@Gateway(requestChannel="toTcpChannel") 
public void sendToTcp(@Payload String message, @Header("myCustomID") Long myCustomID); 

我知道這是一個事件沒有消息,但我不知道怎麼去,我會接受輸入通道以任何其他方式連接ID。

我正在創建一個類型爲my custom id – connection id的哈希映射。 我無法通過聚合器使用自定義關聯,因爲響應消息不會包含有關以前發送的消息的任何信息。任何建議將受到歡迎。

+0

對不起,什麼是問題? 'TcpConnectionOpenEvent'無疑是開始連接,這是真的,沒有任何消息要處理。然而,在這個事件中,你真的可以爲你的未來目的存儲'connectionId'。 –

+0

我需要一個攔截器,我已經有一個連接ID,我仍然有發送通道標題。我的第一種方法是覆蓋TcpSendingMessageHandler。 – crm86

回答

0

哦!我懂了。不知道你要從你的自定義TcpSendingMessageHandler做什麼,但只要ApplicationEventPublisher是單線程的,你可以將connectionId存儲在ThreadLocal變量中,並在發送操作後從那裏獲取它。