如果您想要在ActiveMQ上使用onMessage方法,并使用createDurableSubscriber创建一个持久化的订阅者,则需要向ConnectionFactory添加一个uniqueClientId。这个uniqueClientId将使持久化检查点保存在ActiveMQ中,并将在下一次您启动应用程序时自动恢复。以下是一个使用uniqueClientId的Java示例代码:
public class Consumer implements MessageListener {
public static void main(String[] args) {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection connection = null;
try {
connection = connectionFactory.createConnection();
connection.setClientID("UniqueClientId");
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic myTopic = session.createTopic("MyTopic");
MessageConsumer consumer = session.createDurableSubscriber(myTopic, "mySubscriptionName");
consumer.setMessageListener(new Consumer());
} catch (JMSException e) {
e.printStackTrace();
}
}
public void onMessage(Message message) {
// process received message
}
}