我有一个实现消息生产者的 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();
}
}
任何帮助表示赞赏。