gpt4 book ai didi

java - JMS 队列接收消息?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:33:03 24 4
gpt4 key购买 nike

在 JMS API 文档中,它说:

public Message receive() throws JMSException

Receives the next message produced for this message consumer. This call blocks indefinitely until a message is produced or until this message consumer is closed.

If this receive is done within a transaction, the consumer retains the message until the transaction commits.

这里我有三个问题:1. 在代码中,我们是否需要while循环来接收消息?喜欢:

while(true){
Message msg = queue.receive();
....
}
  1. 交易设置是什么?如何提交交易?像这样:

    boolean transacted = false;
    session = connection.createQueueSession(transacted, Session.AUTO_ACKNOWLEDGE);
  2. receiveNoWait() 有事务支持吗?如何使用它?

谢谢

最佳答案

  1. 如果您打算使用 receive,那么您将需要某种循环以在收到第一个消息后继续接收消息。请记住,您还可以设置消息监听器并通过回调方法异步接收消息,而不必阻塞。

  2. 默认情况下,事务通常设置为 AUTO_ACKNOWLEDGE,这意味着一旦消息从队列中取出,它就会消失并且无法回滚。如果要设置事务,则需要将 session 设置为事务处理并将方法设置为 SESSION_TRANSACTED。当您在 session 中调用 commit() 时,消息将在队列中得到确认。

  3. 如果您正确设置确认模式并在 session 中使用 commit() 和 rollback(),则 receiveNoWait() 可以具有事务支持。

如果我是你,我会创建一个 MessageListener 而不必担心旋转一个线程来轮询接收方法。请记住,一旦 session 创建,隐式事务就会启动。

public class JmsAdapter implements MessageListener, ExceptionListener
{
private ConnectionFactory connFactory = null;
private Connection conn = null;
private Session session = null;

public void receiveMessages()
{
try
{
this.session = this.conn.createSession(true, Session.SESSION_TRANSACTED);

this.conn.setExceptionListener(this);

Destination destination = this.session.createQueue("SOME_QUEUE_NAME");

this.consumer = this.session.createConsumer(destination);

this.consumer.setMessageListener(this);

this.conn.start();
}
catch (JMSException e)
{
//Handle JMS Exceptions Here
}
}

@Override
public void onMessage(Message message)
{
try
{
//Do Message Processing Here

//Message sucessfully processed... Go ahead and commit the transaction.
this.session.commit();
}
catch(SomeApplicationException e)
{
//Message processing failed.
//Do whatever you need to do here for the exception.

//NOTE: You may need to check the redelivery count of this message first
//and just commit it after it fails a predefined number of times (Make sure you
//store it somewhere if you don't want to lose it). This way you're process isn't
//handling the same failed message over and over again.
this.session.rollback()
}
}
}

关于java - JMS 队列接收消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8492499/

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