使用动态主机和端口进行TCP套接字客户端的Spring集成

时间:2019-03-14 13:33:40

标签: spring-boot spring-integration tcpsocket

我有一个使用Spring Integration并带有硬编码主机名和端口的TCPSocketClient的工作示例。

如何修改此示例以接受要动态传递的localhost和端口5877

即是否可以调用像ExchangeService.exchange(hostname, port, request)这样的交换方法而不是ExchangeService.exchange(request)

如果是,那么如何将这些参数应用于client bean?

@Configuration
public class AppConfig {

    @Bean
    public IntegrationFlow client() {
        return IntegrationFlows.from(ApiGateway.class).handle(
            Tcp.outboundGateway(
                Tcp.netClient("localhost", 5877)
                .serializer(codec())
                .deserializer(codec())
            ).remoteTimeout(10000)
        )
        .transform(Transformers.objectToString())
        .get();
    }

    @Bean
    public ByteArrayCrLfSerializer codec() {
        ByteArrayCrLfSerializer crLfSerializer = new ByteArrayCrLfSerializer();
        crLfSerializer.setMaxMessageSize(204800000);
        return crLfSerializer;
    }

    @Bean
    @DependsOn("client")
    public ExchangeService exchangeService(ApiGateway apiGateway) {
        return new ExchangeServiceImpl(apiGateway);
    }
}

public interface ApiGateway {
    String exchange(String out);
}

public interface ExchangeService {
    public String exchange(String request);
}

@Service
public class ExchangeServiceImpl implements ExchangeService {

    private ApiGateway apiGateway;
    @Autowired
    public ExchangeServiceImpl(ApiGateway apiGateway) {
        this.apiGateway=apiGateway;
    }

    @Override
    public String exchange(String request) {
        String response = null;
        try {
            response = apiGateway.exchange(request);
        } catch (Exception e) {
            throw e;
        }
        return response;
    }   
}

1 个答案:

答案 0 :(得分:1)

对于动态处理,您可以考虑使用Spring Integration Java DSL的动态流程功能:https://docs.spring.io/spring-integration/docs/current/reference/html/#java-dsl-runtime-flows

因此,每当您收到带有这些参数的请求时,便会立即创建一个IntegrationFlow并向IntegrationFlowContext注册。坦白地说,我们在文档中为您的TCP用例提供了准确的示例:

IntegrationFlow flow = f -> f
        .handle(Tcp.outboundGateway(Tcp.netClient("localhost", this.server1.getPort())
                .serializer(TcpCodecs.crlf())
                .deserializer(TcpCodecs.lengthHeader1())
                .id("client1"))
            .remoteTimeout(m -> 5000))
        .transform(Transformers.objectToString());

IntegrationFlowRegistration theFlow = this.flowContext.registration(flow).register();