【发布时间】:2021-03-02 13:44:33
【问题描述】:
我有一个 JMS 应用程序,它试图从 JBosss 队列中读取数据。我在课堂上实现了MessageListener,并使用onMessage() 接收消息
public class JBossConnector implements MessageListener, AutoCloseable {}
这是我的方法:
/**
* The listener method of JMS. It listens to messages from queue: 'jbossToAppia'
* If the message is of type MessageObject, then transfer that to Appia
*
* @param message JMS Message
*/
@Override
public void onMessage(Message message) {
// receive the message from jboss queue: 'jbossToAppia'
// then post it to appia
if (message instanceof ObjectMessage) {
try {
MessageObject messageObject = (MessageObject) ((ObjectMessage) message).getObject();
System.out.printf("JbossConnector: MessageObject received from JBOSS, %s\n", messageObject.getMessageType());
component.onMessageFromJboss(properties.getProperty("target.sessionID"), messageObject);
} catch (MessageFormatException exception) {
logger.error(ExceptionHandler.getFormattedException(exception));
ExceptionHandler.printException(exception);
} catch (JMSException exception) {
ExceptionHandler.printException(exception);
restart();
}
} else {
System.out.printf("%s: MessageFormatException(Message is not of the format MessageObject)\n", this.getClass().getSimpleName());
}
}
每当我找到JMSException 时,我都会尝试重新启动 JBoss 连接(上下文、连接、会话、接收方、发送方)。我的疑问是我读过onMessage() 使用多个线程从队列接收消息(如果我错了,请纠正我)。
当 JBoss 队列连接断开时,至少会有一些队列抛出此异常。这意味着他们都会尝试restart() 连接,这是浪费时间(restart() 首先关闭所有连接,将变量设置为 null,然后尝试启动连接)。
现在我可以做类似的事情
synchronized (this){
restart();
}
或使用volatile 变量。但这并不能保证当当前线程完成restart() 操作时其他线程不会尝试restart()(如果我错了,请再次纠正我)。
有什么办法可以解决这个问题吗?
【问题讨论】: