Spring Integration TCP服务器:获取IP地址&有效载荷

时间:2014-08-27 20:13:20

标签: java spring spring-mvc tcp spring-integration

我刚开始使用Spring-Integration,我实现了TCP服务器,它只向客户端发送“OK”消息。我想记录客户端IP地址和从客户端收到的文本。

我能够使用以下配置文件成功获取客户端发送的文本,但我不知道如何获取客户端的IP地址。

以下是TCP服务器的配置文件。

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:int="http://www.springframework.org/schema/integration"
   xmlns:int-ip="http://www.springframework.org/schema/integration/ip"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
    http://www.springframework.org/schema/integration/ip http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">

<context:property-placeholder />
<int-ip:tcp-connection-factory id="tcpServer"
                               type="server"
                               using-nio="true"
                               port="${tcpServer.port}"/>

<int-ip:tcp-inbound-gateway id="tcpGateway"
                            connection-factory="tcpServer"
                            request-channel="bytesChannel"
                            error-channel="errorChannel"/>


<int:service-activator input-channel="inputChannel" ref="myTcpService" method="processInput"/>

<bean id="myTcpService" class="MyTcpService" />

<int:transformer id="transformerBytes2String"
                 input-channel="bytesChannel"
                 output-channel="inputChannel"
                 expression="new String(payload)"/>

<int:transformer id="errorHandler"
                 input-channel="errorChannel"
                 expression="payload.failedMessage.payload + ':' + payload.cause.message"/>

<int:channel id="inputChannel" />
<int:channel id="bytesChannel"/>

</beans>

MyTcpService类:

public class MyTcpService  {
    public String processInput(String input){
       return "OK";
    }
}

我想知道是否可以在“processInput”方法中获取IP地址和有效负载。

1 个答案:

答案 0 :(得分:1)

多个连接属性存储在MessageHeadersTcpMessageMapper)中:

messageBuilder
        .setHeader(IpHeaders.HOSTNAME, connection.getHostName())
        .setHeader(IpHeaders.IP_ADDRESS, connection.getHostAddress())
        .setHeader(IpHeaders.REMOTE_PORT, connection.getPort())
        .setHeader(IpHeaders.CONNECTION_ID, connectionId);

因此,您可以在processInput方法中添加一个参数,以便从所需的标题中获取值:

public String processInput(String input, @Header(IpHeaders.IP_ADDRESS) String ip){

当没有任何注释的input参数仍然映射到payload时。