我正在接收来自 Active MQ 队列的消息。
有没有办法一次接收多条消息?还是必须通过循环来完成?
此外,如果我想说 30 条消息运行一个过程,并且只有当该过程有效时,才会 message.acknowledge();
为所有消息返回一个。
我的意思是如果程序失败,我不想从队列中删除这 30 个。
谢谢。
我正在接收来自 Active MQ 队列的消息。
有没有办法一次接收多条消息?还是必须通过循环来完成?
此外,如果我想说 30 条消息运行一个过程,并且只有当该过程有效时,才会 message.acknowledge();
为所有消息返回一个。
我的意思是如果程序失败,我不想从队列中删除这 30 个。
谢谢。
您必须循环执行。通常,最好使用消息驱动的 bean 来消费消息,但它不适合这种情况,因为它们逐条接收消息并且您无法指定确切的数量。因此,使用MessageConsumer
和手动交易:
@Resource
UserTransaction utx;
@Resource(mappedName="jms/yourConnectionFactory");
ConnectionFactory cf;
@Resource(mappedName="jms/yourQueue");
Queue queue;
..
Connection conn = null;
Session s = null;
MessageConsumer mc = null;
try {
utx.begin();
conn = cf.createConnection();
s = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE); //TRANSACTIONAL SESSION!
mc = s.createConsumer(queue);
conn.start(); // START CONNECTION'S DELIVERY OF INCOMING MESSAGES
for(int i=0; i<30; i++)
{
Message msg = mc.receive();
//BUSINESS LOGIC
}
utx.commit();
} catch(Exception ex) {
..
} finally { //CLOSE CONNECTION, SESSION AND MESSAGE CONSUMER
}
I don't have any experience in ActiveMQ. But I think in case of queue listeners, basic logic should be the same independent to the queue implementation.
For your first question I don't know any way of retrieving multiple messages from a queue. I think best way would be to fetch it one by one inside a loop.
For your second question, message will not be discarded from the queue till the underlying transaction which read the message commits. So you could read whole bunch of messages in a single transaction and roll it back in case of an error. It shouldn't erase any existing messages from the queue.
May I ask why do you need 30 messages to run a procedure. Usually when we use a queue, each message should be able to process independently.