springboot集成integration-ip搭建TCP Client

1、创建客户端属性类

tcp:
  client:
    host: 127.0.0.1
    port: 5001
@Data
@ConfigurationProperties("tcp.client")
public class TcpClientProperties {

    private String host;

    private Integer port;
}

2、集成integration-ip配置

@Slf4j
@Configuration
@EnableConfigurationProperties(TcpClientProperties.class)
public class TcpClientConfig {

    @Autowired
    private TcpClientProperties properties;


    @Bean
    public AbstractClientConnectionFactory clientConnectionFactory() {
        TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory(properties.getHost(), properties.getPort());
        factory.setSingleUse(false);
        factory.setSerializer(new TcpClientSerializer());
        factory.setDeserializer(new TcpClientSerializer());
        return factory;
    }

    @Bean
    public MessageChannel inboundChannel() {
        return new DirectChannel();
    }

    @Bean
    public TcpReceivingChannelAdapter tcpInbound(AbstractClientConnectionFactory connectionFactory) {
        TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
        adapter.setConnectionFactory(connectionFactory);
        adapter.setOutputChannel(inboundChannel());
        adapter.setClientMode(true);
        adapter.setRetryInterval(5000);
        return adapter;
    }

    @ServiceActivator(inputChannel = "inboundChannel")
    public void handleMessage(byte[] message) {
        String receivedMessage = new String(message);
        log.info("Received message: {}", receivedMessage);
    }
}

3、实现自定义序列化器

public class TcpClientSerializer implements Serializer<byte[]>, Deserializer<byte[]> {
    @Override
    public byte[] deserialize(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int data;
        while ((data = inputStream.read()) != -1) {
            buffer.write(data);
            if (inputStream.available() == 0) {
                break;
            }
        }
        return buffer.toByteArray();
    }

    @Override
    public void serialize(byte[] bytes, OutputStream outputStream) throws IOException {
        outputStream.write(bytes);
        outputStream.flush();
    }
}

 

posted @ 2024-08-13 13:48  方大帝的博客  阅读(136)  评论(0编辑  收藏  举报