gpt4 book ai didi

java - 如何在 Spring Integration DSL 中实现简单的 echo 套接字服务

转载 作者:行者123 更新时间:2023-12-02 01:36:39 25 4
gpt4 key购买 nike

请,
您能帮助在 Spring Integration DSL 中实现一个简单的 echo 风格的 Heartbeat TCP 套接字服务吗?更准确地说,如何将 Adapter/Handler/Gateway 插入客户端和服务器端的 IntegrationFlows。 Spring Integration DSL 和 TCP/IP 客户端/服务器通信的实际示例很难找到。

我认为,我已经完成了大部分代码,只是将所有内容插入到 IntegrationFlow 中。

SI 示例中有一个示例 echo 服务,但它是用“旧”XML 配置编写的,我真的很难通过代码将其转换为配置。

我的心跳服务是一个简单的服务器,等待客户端询问“状态”,并以“确定”响应。

没有@ServiceActivator,没有@MessageGateways,没有代理,一切都明确而详细;由客户端的普通 JDK 调度执行器驱动;服务器和客户端位于单独的配置和项目中。

HeartbeatClientConfig

@Configuration
@EnableIntegration
public class HeartbeatClientConfig {

@Bean
public MessageChannel outboudChannel() {
return new DirectChannel();
}

@Bean
public PollableChannel inboundChannel() {
return new QueueChannel();
}

@Bean
public TcpNetClientConnectionFactory connectionFactory() {
TcpNetClientConnectionFactory connectionFactory = new TcpNetClientConnectionFactory("localhost", 7777);
return connectionFactory;
}

@Bean
public TcpReceivingChannelAdapter heartbeatReceivingMessageAdapter(
TcpNetClientConnectionFactory connectionFactory,
MessageChannel inboundChannel) {
TcpReceivingChannelAdapter heartbeatReceivingMessageAdapter = new TcpReceivingChannelAdapter();
heartbeatReceivingMessageAdapter.setConnectionFactory(connectionFactory);
heartbeatReceivingMessageAdapter.setOutputChannel(inboundChannel); // ???
heartbeatReceivingMessageAdapter.setClientMode(true);
return heartbeatReceivingMessageAdapter;
}

@Bean
public TcpSendingMessageHandler heartbeatSendingMessageHandler(
TcpNetClientConnectionFactory connectionFactory) {
TcpSendingMessageHandler heartbeatSendingMessageHandler = new TcpSendingMessageHandler();
heartbeatSendingMessageHandler.setConnectionFactory(connectionFactory);
return heartbeatSendingMessageHandler;
}

@Bean
public IntegrationFlow heartbeatClientFlow(
TcpNetClientConnectionFactory connectionFactory,
TcpReceivingChannelAdapter heartbeatReceivingMessageAdapter,
TcpSendingMessageHandler heartbeatSendingMessageHandler,
MessageChannel outboudChannel) {
return IntegrationFlows
.from(outboudChannel) // ??????
.// adapter ???????????
.// gateway ???????????
.// handler ???????????
.get();
}

@Bean
public HeartbeatClient heartbeatClient(
MessageChannel outboudChannel,
PollableChannel inboundChannel) {
return new HeartbeatClient(outboudChannel, inboundChannel);
}
}

HeartbeatClient

public class HeartbeatClient {
private final MessageChannel outboudChannel;
private final PollableChannel inboundChannel;
private final Logger log = LogManager.getLogger(HeartbeatClient.class);

public HeartbeatClient(MessageChannel outboudChannel, PollableChannel inboundChannel) {
this.inboundChannel = inboundChannel;
this.outboudChannel = outboudChannel;
}

@EventListener
public void initializaAfterContextIsReady(ContextRefreshedEvent event) {
log.info("Starting Heartbeat client...");
start();
}

public void start() {
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
while (true) {
try {
log.info("Sending Heartbeat");
outboudChannel.send(new GenericMessage<String>("status"));
Message<?> message = inboundChannel.receive(1000);
if (message == null) {
log.error("Heartbeat timeouted");
} else {
String messageStr = new String((byte[]) message.getPayload());
if (messageStr.equals("OK")) {
log.info("Heartbeat OK response received");
} else {
log.error("Unexpected message content from server: " + messageStr);
}
}
} catch (Exception e) {
log.error(e);
}
}
}, 0, 10000, TimeUnit.SECONDS);
}
}

HeartbeatServerConfig

@Configuration
@EnableIntegration
public class HeartbeatServerConfig {

@Bean
public MessageChannel outboudChannel() {
return new DirectChannel();
}

@Bean
public PollableChannel inboundChannel() {
return new QueueChannel();
}

@Bean
public TcpNetServerConnectionFactory connectionFactory() {
TcpNetServerConnectionFactory connectionFactory = new TcpNetServerConnectionFactory(7777);
return connectionFactory;
}

@Bean
public TcpReceivingChannelAdapter heartbeatReceivingMessageAdapter(
TcpNetServerConnectionFactory connectionFactory,
MessageChannel outboudChannel) {
TcpReceivingChannelAdapter heartbeatReceivingMessageAdapter = new TcpReceivingChannelAdapter();
heartbeatReceivingMessageAdapter.setConnectionFactory(connectionFactory);
heartbeatReceivingMessageAdapter.setOutputChannel(outboudChannel);
return heartbeatReceivingMessageAdapter;
}

@Bean
public TcpSendingMessageHandler heartbeatSendingMessageHandler(
TcpNetServerConnectionFactory connectionFactory) {
TcpSendingMessageHandler heartbeatSendingMessageHandler = new TcpSendingMessageHandler();
heartbeatSendingMessageHandler.setConnectionFactory(connectionFactory);
return heartbeatSendingMessageHandler;
}

@Bean
public IntegrationFlow heartbeatServerFlow(
TcpReceivingChannelAdapter heartbeatReceivingMessageAdapter,
TcpSendingMessageHandler heartbeatSendingMessageHandler,
MessageChannel outboudChannel) {
return IntegrationFlows
.from(heartbeatReceivingMessageAdapter) // ???????????????
.handle(heartbeatSendingMessageHandler) // ???????????????
.get();
}

@Bean
public HeartbeatServer heartbeatServer(
PollableChannel inboundChannel,
MessageChannel outboudChannel) {
return new HeartbeatServer(inboundChannel, outboudChannel);
}
}

心跳服务器

public class HeartbeatServer {
private final PollableChannel inboundChannel;
private final MessageChannel outboudChannel;
private final Logger log = LogManager.getLogger(HeartbeatServer.class);

public HeartbeatServer(PollableChannel inboundChannel, MessageChannel outboudChannel) {
this.inboundChannel = inboundChannel;
this.outboudChannel = outboudChannel;
}

@EventListener
public void initializaAfterContextIsReady(ContextRefreshedEvent event) {
log.info("Starting Heartbeat");
start();
}

public void start() {
Executors.newSingleThreadExecutor().execute(() -> {
while (true) {
try {
Message<?> message = inboundChannel.receive(1000);
if (message == null) {
log.error("Heartbeat timeouted");
} else {
String messageStr = new String((byte[]) message.getPayload());
if (messageStr.equals("status")) {
log.info("Heartbeat received");
outboudChannel.send(new GenericMessage<>("OK"));
} else {
log.error("Unexpected message content from client: " + messageStr);
}
}
} catch (Exception e) {
log.error(e);
}
}
});
}
}

奖励问题

为什么 channel 可以在TcpReceivingChannelAdapter(入站适配器)上设置,但不能在TcpSendingMessageHandler(出站适配器)上设置?

更新
如果有人有兴趣的话,这里是完整的项目源代码:
https://bitbucket.org/espinosa/spring-integration-tcp-demo
我会尝试将所有建议的解决方案放在那里。

最佳答案

使用 DSL 就简单多了...

@SpringBootApplication
@EnableScheduling
public class So55154418Application {

public static void main(String[] args) {
SpringApplication.run(So55154418Application.class, args);
}

@Bean
public IntegrationFlow server() {
return IntegrationFlows.from(Tcp.inboundGateway(Tcp.netServer(1234)))
.transform(Transformers.objectToString())
.log()
.handle((p, h) -> "OK")
.get();
}

@Bean
public IntegrationFlow client() {
return IntegrationFlows.from(Gate.class)
.handle(Tcp.outboundGateway(Tcp.netClient("localhost", 1234)))
.transform(Transformers.objectToString())
.handle((p, h) -> {
System.out.println("Received:" + p);
return null;
})
.get();
}

@Bean
@DependsOn("client")
public Runner runner(Gate gateway) {
return new Runner(gateway);
}

public static class Runner {

private final Gate gateway;

public Runner(Gate gateway) {
this.gateway = gateway;
}

@Scheduled(fixedDelay = 5000)
public void run() {
this.gateway.send("foo");
}

}

public interface Gate {

void send(String out);

}

}

或者,从 Gate 方法获取回复...

    @Bean
public IntegrationFlow client() {
return IntegrationFlows.from(Gate.class)
.handle(Tcp.outboundGateway(Tcp.netClient("localhost", 1234)))
.transform(Transformers.objectToString())
.get();
}

@Bean
@DependsOn("client")
public Runner runner(Gate gateway) {
return new Runner(gateway);
}

public static class Runner {

private final Gate gateway;

public Runner(Gate gateway) {
this.gateway = gateway;
}

@Scheduled(fixedDelay = 5000)
public void run() {
String reply = this.gateway.sendAndReceive("foo"); // null for timeout
System.out.println("Received:" + reply);
}

}

public interface Gate {

@Gateway(replyTimeout = 5000)
String sendAndReceive(String out);

}

奖金:

消费端点实际上由 2 个 bean 组成;消费者和消息处理程序。该 channel 面向消费者。请参阅here .

编辑

另一种选择,为客户端提供单个 bean...

@Bean
public IntegrationFlow client() {
return IntegrationFlows.from(() -> "foo",
e -> e.poller(Pollers.fixedDelay(Duration.ofSeconds(5))))
.handle(Tcp.outboundGateway(Tcp.netClient("localhost", 1234)))
.transform(Transformers.objectToString())
.handle((p, h) -> {
System.out.println("Received:" + p);
return null;
})
.get();
}

关于java - 如何在 Spring Integration DSL 中实现简单的 echo 套接字服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55154418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com