gpt4 book ai didi

java - 如何在Spring中正确终止 Activity 的套接字连接?

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

我使用套接字连接作为客户端,spring-integration-ip:

@Bean
public AbstractClientConnectionFactory clientFactory() throws Exception {
TcpConnectionFactoryFactoryBean f = new TcpConnectionFactoryFactoryBean();
f.setType("client");
f.setHost(host);
f.setPort(port);
...
}

@Bean
@ServiceActivator(inputChannel = "clientChannel")
public TcpOutboundGateway outboundGatewasy(AbstractClientConnectionFactory factory) throws Exception {
TcpOutboundGateway g = new TcpOutboundGateway();
g.setConnectionFactory(factory);
g.setRequiresReply(true);
return gate;
}

现在我可以注入(inject)@Autowired TcpOutboundGateway gateway。但没有像 .beforeShutdown()getActiveConnections() 这样的方法。

那么,当应用程序关闭时,如何检索 Activity 的套接字连接?

最佳答案

连接由连接工厂而不是网关管理。

改为 Autowiring 连接工厂,并使用 getOpenConnectionIds()

使用closeConnection(String connectionId)关闭连接。

编辑

@SpringBootApplication
public class So44760185Application {

public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(So44760185Application.class, args);
MessageChannel channel = context.getBean("clientChannel", MessageChannel.class);
try {
channel.send(new GenericMessage<>("foo"));
System.err.println("Expected ConnectException");
}
catch (MessagingException e) {
if (!(e.getCause().getCause() instanceof ConnectException)) {
throw e;
}
System.out.println("good1");
}

context.getBean(ShuttingDownAdvice.class).shuttingDown = true;

try {
channel.send(new GenericMessage<>("foo"));
System.err.println("Expected shutting down exception");
}
catch (MessagingException e) {
if (!(e.getCause().getMessage().equals("No new connections allowed"))) {
throw e;
}
System.out.println("good2");
}
context.close();
}

@Bean
public static TcpConnectionFactoryFactoryBean connectionFactoryBean() {
TcpConnectionFactoryFactoryBean f = new TcpConnectionFactoryFactoryBean();
f.setType("client");
f.setHost("localhost");
f.setPort(1234);
return f;
}

@Bean
@ServiceActivator(inputChannel = "clientChannel")
public TcpOutboundGateway outboundGateway(AbstractClientConnectionFactory factory) throws Exception {
TcpOutboundGateway g = new TcpOutboundGateway();
g.setConnectionFactory(factory);
g.setRequiresReply(true);
g.setAdviceChain(Collections.singletonList(advice()));
return g;
}

@Bean
public ShuttingDownAdvice advice() {
return new ShuttingDownAdvice();
}

public static class ShuttingDownAdvice extends AbstractRequestHandlerAdvice {

private volatile boolean shuttingDown;

@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
if (this.shuttingDown) {
throw new RuntimeException("No new connections allowed");
}
return callback.execute();
}

}

}

关于java - 如何在Spring中正确终止 Activity 的套接字连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44760185/

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