vis*_*hva 6 activemq-classic jms jakarta-ee
我正在尝试在我的项目中实现 JMS。我使用 active mq 作为提供者,并使用持久队列。以下是从活动 mq 中检索元素的代码
conn = GlobalConfiguration.getJMSConnectionFactory().createConnection();
conn.start();
session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
ObjectMessage obj = (ObjectMessage) consumer.receiveNoWait();
Run Code Online (Sandbox Code Playgroud)
此代码有时会返回数据,有时会返回 null,即使我可以在活动 mq 管理控制台中看到待处理消息的数量为非零。我读了很多文章,很少有人提到 JMS api 并不要求您每次都获取该元素,并且您必须相应地进行编码。因为在我的场景中,我依赖于队列,一旦队列返回 null,我就会终止进程,所以我按以下方式修改了代码
我没有调用 receiveNoWait,而是通过队列浏览器检查队列中是否存在元素后开始使用 receive。以下是修改后的代码
public static <T> T retrieveObjectFromQueue(Queue queue, Class<T> clazz) {
synchronized (queue) {
if(!queueHasMoreElements(queue))
return null;
Connection conn = null;
Session session = null;
try {
conn = GlobalConfiguration.getJMSConnectionFactory().createConnection();
conn.start();
session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
ObjectMessage obj = (ObjectMessage) consumer.receive();
return clazz.cast(obj.getObject());
} catch(Exception e) {
throw new RuntimeException(e);
}finally {
closeSessionAndConnection(session, conn);
}
}
public static boolean queueHasMoreElements(Queue queue) {
Connection conn = null;
Session session = null;
try {
conn = GlobalConfiguration.getJMSConnectionFactory().createConnection();
conn.start();
session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
QueueBrowser browser = session.createBrowser(queue);
Enumeration enumeration = browser.getEnumeration();
return enumeration.hasMoreElements();
} catch(Exception e) {
throw new RuntimeException(e);
}finally {
closeSessionAndConnection(session, conn);
}
Run Code Online (Sandbox Code Playgroud)
现在,我的代码在处理大约 20-30 个元素后卡住了,而且我可以在管理控制台中看到待处理的元素。当我尝试使用调试模式时,我意识到,在检索 20-30 个元素后,我的代码卡在Consumer.receive()处,这是预期的情况,以防队列为空,但当我检查我的管理控制台时,它显示了很多队列中的元素数。
我使用 jdbc(mysql) 作为 activemq 的持久存储。我使用的配置 xml 如 activemq 配置示例 (activemq/examples/conf/activemq-jdbc-performance.xml) 中给出的
我使用 tcp://localhost:61616?jms.prefetchPolicy.queuePrefetch=1 作为 activemq url。
请让我知道我做错了什么。我正在使用 java8 和 apache activeMq 5.13.1
谢谢
JMS 规范也没有强制要求 QueueBrowser 返回队列中的所有消息,您可能只能在启动时获得其中的快照,具体取决于许多因素。
您试图将其无法保证的语义强加于 JMS。您可以尝试将预取设置为零,这将导致客户端轮询代理以获取消息,并等待代理告知有或没有消息。如果轮询时消息尚未进入队列,您可能仍然什么也得不到,这只是您需要处理的事情。
您还可以使用定时接收方法,并在返回和终止应用程序之前施加您愿意等待的超时。
| 归档时间: |
|
| 查看次数: |
1762 次 |
| 最近记录: |