我有一个使用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;
}
}
答案 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();