gpt4 book ai didi

java - 如何捕获 spring-integration 套接字服务器中的错误?

转载 作者:行者123 更新时间:2023-11-30 06:08:06 26 4
gpt4 key购买 nike

我有以下工作套接字服务器配置,并且希望在发生任何异常时添加一个处理程序,例如在读取消息期间在反序列化器内。

因此我添加了一个@ServiceActivator(inputChannel = "errorChannel")。但该方法从未被调用。为什么?

@MessageEndpoint
public class SocketEndpoint {
@ServiceActivator(inputChannel = "mainChannel")
public String handleMessage(String message) {
return "normal response";

}

@ServiceActivator(inputChannel = "errorChannel")
public String handleError(MessagingException message) {
//TODO this is never invoked!
return "some error";
}
}

@Bean
public TcpInboundGateway mainGateway(
@Qualifier("tcpFactory") TcpConnectionFactoryFactoryBean factory,
@Qualifier("mainChannel") MessageChannel mainChannel,
@Qualifier("errorChannel") MessageChannel errorChannel) throws Exception {
TcpInboundGateway g = new TcpInboundGateway();
g.setConnectionFactory(factory.getObject());
g.setRequestChannel(mainChannel);
g.setErrorChannel(errorChannel);
return g;
}

@Bean
public TcpConnectionFactoryFactoryBean fact() {
TcpConnectionFactoryFactoryBean f = new TcpConnectionFactoryFactoryBean();
f.setType("server");
//....
f.setDeserializer(new MyDeserializer());
return f;
}

class MyDeserializer implements Deserializer<String> {
@Override
public String deserialize(InputStream inputStream)
throw new RuntimeException("catch me in error-channel");
}
}

最佳答案

throw new RuntimeException("catch me in error-channel");

它无法进入错误 channel ,因为还没有消息(发送到错误 channel 的消息是下游处理失败的消息)。

标准反序列化器(扩展 AbstractByteArraySerializer )发布 TcpDeserializationExceptionEvent当反序列化失败时。请参阅ByteArrayCrLfSerializer举个例子:

https://github.com/spring-projects/spring-integration/blob/master/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/serializer/ByteArrayCrLfSerializer.java#L78

public int fillToCrLf(InputStream inputStream, byte[] buffer) throws IOException {
int n = 0;
int bite;
if (logger.isDebugEnabled()) {
logger.debug("Available to read: " + inputStream.available());
}
try {
...
}
catch (SoftEndOfStreamException e) {
throw e;
}
catch (IOException e) {
publishEvent(e, buffer, n);
throw e;
}
catch (RuntimeException e) {
publishEvent(e, buffer, n);
throw e;
}
}

参见the documentationDeserializer需要是一个 bean,这样它才能获得事件发布者。

然后您可以使用 ApplicationListener< TcpDeserializationExceptionEvent> 监听事件或@EventListener方法。

关于java - 如何捕获 spring-integration 套接字服务器中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50855664/

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