【发布时间】:2020-08-14 15:13:50
【问题描述】:
我有一个关于消息驱动 Bean (MDB) 的问题。有没有办法只在运行时生成这些?我想在我的后端提供一种方法来开始或停止接收消息。它应该通过数据库中的配置条目进行控制。在启动 WildFly 时,还应首先检查 MDB 是否可以启动。
在没有 MDB 的情况下手动创建侦听器是否符合 Java EE?
我目前正在使用以下代码
@MessageDriven(name = "MyMDB", activationConfig = {
@ActivationConfigProperty(propertyName = "maxSession", propertyValue = "2"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "java:/jms/queue/Test"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge")})
public class JmsConsumer implements MessageListener {
@Override
public void onMessage(final Message msg) {
if (msg instanceof TextMessage) {
try {
final String text = ((TextMessage) msg).getText();
System.out.println("message: " + text + " (" + msg.getJMSRedelivered() + ")");
} catch (final JMSException e) {
e.printStackTrace();
}
}
}
}
此代码是否也符合 Java EE?
@Singleton
@LocalBean
public class QueueWorkerManager {
private InitialContext initialContext = null;
private QueueConnectionFactory queueConnectionFactory = null;
private Queue queue = null;
private QueueConnection queueConnection = null;
private QueueSession queueSession = null;
private MessageConsumer consumer = null;
@PostConstruct
public void init() {
try {
this.initialContext = new InitialContext();
this.queueConnectionFactory = (QueueConnectionFactory) initialContext
.lookup("java:/ConnectionFactory");
this.queue = (Queue) initialContext.lookup(MyQueueSender.WORKER_QUEUE);
this.queueConnection = queueConnectionFactory.createQueueConnection();
this.queueSession = queueConnection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
this.consumer = queueSession.createConsumer(this.queue);
this.consumer.setMessageListener(new ConsumerMessageListener());
this.queueConnection.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
@PreDestroy
public void destroy() {
this.stopConsumer(this.consumer;
if(this.consumer != null) {
try {
this.consumer.close();
} catch (JMSException e) {
}
this.consumer = null;
}
if(this.queueSession != null) {
try {
this.queueSession.close();
} catch (JMSException e) {
}
this.queueSession = null;
}
if(this.queueConnection != null) {
try {
this.queueConnection.close();
} catch (JMSException e) {
}
this.queueConnection = null;
}
}
}
public class ConsumerMessageListener implements MessageListener {
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("message: " + textMessage.getText() + " (" + msg.getJMSRedelivered() + ")");
message.acknowledge();
} catch (JMSException | InterruptedException e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
暂停队列怎么样? activemq.apache.org/components/artemis/documentation/latest/… QueueControl 可以暂停和恢复底层队列。当队列暂停时,它将接收消息但不会传递它们。恢复后,它将开始传递排队的消息(如果有)。
-
我已经阅读了所描述的选项。不幸的是,消息传递的完全中断不是我的目标。我正在寻找一种停用单个 MDB 实例的方法。我可以使用 MDB 名称或类名称来识别实例。