关于java:如何理解JMS中的“同步”和“异步”消息?

How to understand the “synchronous” and “asynchronouns” messaging in JMS?

在阅读了一些JMS的文档之后,我完全困惑于"EDOCX1"(0)和"EDOCX1"(1)。

请参见本页:http://docs.oracle.com/cd/e19798-01/821-1841/bncdq/index.html

同步的

You use the receive method to consume a message synchronously.
You can use this method at any time after you call the start method:

1
2
3
4
connection.start();
Message m = consumer.receive();
connection.start();
Message m = consumer.receive(1000); // time out after a second

To consume a message asynchronously, you use a message listener, described in the next section.

异步的

JMS Message Listeners
A message listener is an object that acts as an asynchronous event handler for messages. This object implements the MessageListener interface, which contains one method, onMessage. In the onMessage method, you define the actions to be taken when a message arrives.

You register the message listener with a specific MessageConsumer by using the setMessageListener method. For example, if you define a class named Listener that implements the MessageListener interface, you can register the message listener as follows:

1
2
Listener myListener = new Listener();
consumer.setMessageListener(myListener);

我有两个问题:

  • 正如我所理解的,JMS的本质是异步的。生产者将消息发布到队列/主题,不需要等待使用者。这是异步行为。如何才能"同步"?

  • 如果"mesagelistener"是异步的,但是在我使用SpringJMS进行的测试中,我发现它总是在线程中运行。这意味着,如果我在onMessage中写入Thread.sleep(2000),它必须等待2秒钟才能处理下一条消息。它是"异步"的吗?


  • 如果您更好地理解它,consumer.receive()使用拉模型:您从队列中读取,并被阻止等待此消息出现,或者超时。

    使用监听器使用推送模型:注册监听器,当消息传入时,在单独的线程中调用监听器。

    一切都是用Java中的线程完成的,而且侦听器调用也不例外。侦听器消息处理是否阻止处理队列中的其他消息,取决于专用于消息处理的线程数。如果将Spring配置为使用5个线程的池异步处理消息,那么5个侦听器将能够并行处理消息。


    就像我理解的那样:

    异步消息侦听器:在侦听队列的服务器上使用它。当消息到达时,立即处理它。服务器一直在侦听此队列。

    同步-consumer.receive(1000):在客户端应用程序上使用它,该应用程序现在需要检查消息是否适合此客户端。示例:每60秒轮询一次。这只会很快打开到服务器的连接。1000毫秒将保持此连接打开。如果消息在1000毫秒内到达,那么消息将被消耗,并且连接将关闭。


    从出版商到消费者,您将看到它的端到端。是的,它是从发布服务器到使用者的异步传递,与同步/异步使用者无关。然而,在您的问题中,同步/异步只针对消费者,即从JMS代理(例如:ApacheMQ)到消费者。正如其他人指出的那样,同步消费者从代理中按顺序提取消息,并等待消息。异步使用者注册一个回调,其中消息被推送到它们(onmessage)。当这些消息从JMS代理异步传递给异步使用者时,异步使用者可以做其他事情。