我有一个正在侦听ActiveMQ队列的Spring Boot应用程序。
有没有办法告诉ActiveMQ保留消费的消息,直到它收到确认从我的服务中删除消息?
我的场景是我从队列中读取消息,一旦消耗,我就将其发送到外部队列。如果外部服务无法处理消息,我会松开消息。在那里我可以告诉活动的mq保持消费的消息,直到它收到删除的确认。
答案 0 :(得分:1)
最安全的选择是使用XA事务以原子方式执行使用/发送(假设您发送消息的代理支持XA)。我不确定Spring有多容易或多么困难,但我知道它在Java EE容器中非常简单。
答案 1 :(得分:0)
您可以使用单个确认模式来确认单个消息。以下是相同的代码:
import javax.jms.Connection;
import javax.jms.JMSException;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQMessageConsumer;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.command.ActiveMQTextMessage;
public class SimpleConsumer {
public static void main(String[] args) throws JMSException {
Connection conn = null;
try {
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
conn = cf.createConnection("consumer", "consumer");
ActiveMQSession session = (ActiveMQSession) conn.createSession(false,
ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session
.createConsumer(session.createQueue("QUEUE"));
conn.start();
ActiveMQTextMessage msg = null;
while ((msg = (ActiveMQTextMessage) consumer.receive()) != null) {
System.out.println("Received message is: " + msg.getText());
// Call your service and ack the message if successfully processed
msg.acknowledge();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
}
}