8 months ago

TCP跟UDP最大的差別就是驗證,它會反覆確認資料是否正確,若資料不正確會要求重新送封包直到資料正確為止,因此這個步驟會花上一點時間。然而當可靠性大於時效性時,大多會使用TCP方式來進行連線,反之。

Integration Config

不得不說TCP設定麻煩了許多,這邊我將介紹直接寫在程式碼註解上會比較好理解。

@Configuration
@EnableIntegration
public class TcpIntegrationConfig {

    // 訊息處理邏輯

    @Bean
    public TcpMessageHandler tcpMessageHandler() {
        return new TcpMessageHandler();
    }
    
  // Connection資料設定,這邊要注意Serializer與Deserializer,跟通訊協定有關係

    @Bean
    public AbstractConnectionFactory tcpNetServerConnectionFactory() {
        TcpNetServerConnectionFactory tcpNetServerConnectionFactory = new TcpNetServerConnectionFactory(1234);
        tcpNetServerConnectionFactory.setSerializer(new ByteArrayRawSerializer());
        tcpNetServerConnectionFactory.setDeserializer(new ByteArrayRawSerializer());
        tcpNetServerConnectionFactory.setSingleUse(true);
        return tcpNetServerConnectionFactory;
    }
    
  // 輸入通道

    @Bean
    public MessageChannel inChannel() {
        return new DirectChannel();
    } 
    
  // 輸出通道

    @Bean
    public MessageChannel outChannel() {
        return new DirectChannel();
    } 
    
  // TCP Channel Adapter,將這個端點的輸出通道給inChannel並且指定上面所設定的連線資訊

    @Bean
    public TcpReceivingChannelAdapter tcpInboundChannelAdapter() {
        TcpReceivingChannelAdapter tcpReceivingChannelAdapter = new TcpReceivingChannelAdapter();
        tcpReceivingChannelAdapter.setOutputChannel(inChannel());
        tcpReceivingChannelAdapter.setConnectionFactory(tcpNetServerConnectionFactory());
        return tcpReceivingChannelAdapter;
    }
    
  // 有接受就有送出,TcpSendingMessageHandler其實就是out bound的部分

    @ServiceActivator(inputChannel = "outChannel")
    @Bean
    public TcpSendingMessageHandler out(AbstractConnectionFactory connectionFactory) {
        TcpSendingMessageHandler out = new TcpSendingMessageHandler();
        out.setConnectionFactory(connectionFactory);
        return out;
    }
    
  // 這邊不太好解釋,大致上是說該端點資料取得後,丟到tcpMessageHandler進行處理,並且回傳資訊。

    @Bean
    public IntegrationFlow integrationFlow() {
        return IntegrationFlows
                .from(tcpInboundChannelAdapter())
                .handle(tcpMessageHandler())
                .channel("outChannel")
                .get();
    }
    
}

MessageHandler

這邊使用AbstractReplyProducingMessageHandler,這個物件可以幫助我們回傳資訊

public class TcpMessageHandler extends AbstractReplyProducingMessageHandler {

    private static Logger logger = LogManager.getLogger(TcpMessageHandler.class);
    
    @Override
    protected Object handleRequestMessage(Message<?> requestMessage) {
        String data = new String((byte[]) requestMessage.getPayload(), StandardCharsets.UTF_8);
        logger.info(data);
        return data;
    }

}

Socket

public class TcpClient {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        
        @SuppressWarnings("resource")
        Socket client = new Socket("localhost", 1234);
        
        String sentence = in.readLine();
        byte[] sendData = sentence.getBytes();
        
        BufferedOutputStream outputStream = new BufferedOutputStream(client.getOutputStream());
        outputStream.write(sendData);
        outputStream.flush();
        client.shutdownOutput();
        
        BufferedInputStream inputStream = new BufferedInputStream(client.getInputStream());
        byte[] b = new byte[1024];
        String data = "";
        int length;
        while ((length = inputStream.read(b)) > 0) { // <=0的話就是結束了

            data += new String(b, 0, length);
        }
        System.out.println(data);
        
        client.close();
    }
}

App

public class TcpApp {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TcpIntegrationConfig.class);
        context.start();
    }
}

Result

大家可以看到運行結果,Client丟一個Hello World字串回去,Server接收到後會原封不動丟回來。

Refenrence

WIKI - 企業應用整合
EAI技術和概念解析

← [Spring MVC] CH 4.1 Spring Integration UDP [Spring MVC] CH 4. Spring Integration →
 
comments powered by Disqus