Reputation: 864
I have a working example of TCPSocketClient using Spring Integration with hard coded host name and the port.
How to modify this example to accept the localhost
and the port 5877
to be passed dynamically?
i.e. Is it possible to call the exchange method like ExchangeService.exchange(hostname, port, request)
instead of ExchangeService.exchange(request)
If so how does those parameter be applied on to the 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;
}
}
Upvotes: 1
Views: 1118
Reputation: 121282
For dynamic processing you may consider to use a Dynamic Flows feature from Spring Integration Java DSL: https://docs.spring.io/spring-integration/docs/current/reference/html/#java-dsl-runtime-flows
So, whenever you receive a request with those parameters, you create an IntegrationFlow
on the fly and register it with the IntegrationFlowContext
. Frankly, we have exactly sample in the docs for your TCP use-case:
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();
Upvotes: 1