我有一个实现消息生成器的Java类,它将消息发送到名为test的队列。我有另一个类作为客户端,它从同一队列中获取消息。我很困惑如何知道客户端是否收到了该消息。我在某处读到了我应该使用message.acknowledge()
,但我不知道这样做的正确方法。我的代码如下所示:
制片:
public class Producer {
private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private static String subject = "que";
public static void main(String[] args) throws JMSException,
InterruptedException {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(subject);
MessageProducer producer = session.createProducer(destination);
//
int i = 0;
//while(true)
// {
TextMessage message = session
.createTextMessage("this is a gfjfjf " + i);
Thread.sleep(2000);
//
producer.send(message);
i++;
System.out.println("Sent message '" + message.getText() + "'");
System.out.println(ActiveMQConnection.DEFAULT_BROKER_URL);
MessageListener ML = session.getMessageListener();
System.out.println(ML);
connection.close();
}
}
消费者:
public class Consumer {
private static String url = "failover://tcp://192.168.1.17:61616";
private static String subject = "que";
public static void main(String[] args) throws JMSException {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(subject);
MessageConsumer consumer = session.createConsumer(destination);
// while(true)
// {
Message message = consumer.receive();
System.out.println(message);
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println("Received message '" + textMessage.getText()
+ "'");
}
if (session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) {
System.out.println(session.getAcknowledgeMode());
System.out.println(Session.CLIENT_ACKNOWLEDGE);
message.acknowledge();
}
System.out.println(session.getAcknowledgeMode());
System.out.println(Session.CLIENT_ACKNOWLEDGE);
message.acknowledge();
}
}
任何帮助表示感谢。
答案 0 :(得分:2)
您无法使用确认来检查是否已收到消息。
实际上,一般情况下的消息传递和特别是JMS的设计使得发送应用程序不需要知道消息是否已到达客户端。这个概念被称为保证交付。
致谢是其中的一部分。如果您读取队列的消息但未确认,则JMS代理将尝试在以后重新发送消息。您可以使用您可以提交或回滚的事务将概念提升到另一个级别。
如果您确实需要收到邮件的原始发件人,我建议您发送邮件回复。 JMS具有使用相关ID和ReplyTo字段的请求/回复的原理图。你可以上传很多例子,但here is one at EIP。