繁体   English   中英

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

[英]Spring Integration for TCP Socket Client using Dynamic Host and Port

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

如何修改这个例子来接受localhost5877端口动态传递?

即是否可以调用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;
    }   
}

对于动态处理,您可以考虑使用 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM