首页 > 其他分享 >springboot集成integration-ip搭建TCP Client

springboot集成integration-ip搭建TCP Client

时间:2024-08-13 13:50:15浏览次数:13  
标签:return springboot ip adapter integration factory class new public

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();
    }
}

 

标签:return,springboot,ip,adapter,integration,factory,class,new,public
From: https://www.cnblogs.com/fangts/p/18356728

相关文章