你可以做一个简单的测试来理解这个概念。如何创建生产者和消费者,请参考教程here。
你会看到producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
改成producer.setDeliveryMode(DeliveryMode.PERSISTENT);
现在创建两个类。一个只调用生产者,一个只调用消费者。
public class AppOnlyProduce {
public static void thread(Runnable runnable, boolean daemon) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(daemon);
brokerThread.start();
}
public static void main(String[] args) throws InterruptedException {
thread(new HelloWorldProducer(), false);
thread(new HelloWorldProducer(), false);
}
}
public class AppOnlyConsumer {
public static void thread(Runnable runnable, boolean daemon) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(daemon);
brokerThread.start();
}
public static void main(String[] args) throws InterruptedException {
thread(new HelloWorldConsumer(), false);
thread(new HelloWorldConsumer(), false);
}
}
首先运行 AppOnlyProduce。它将创建两条消息。现在运行 AppOnlyConsumer 它将读取两条消息。
现在将行改回producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
再次运行 AppOnlyProduce。它将创建两条消息。现在运行 AppOnlyConsumer 你会看到它等待了一段时间的消息,他们说Received: null
在第一种情况下,模式是持久的。因此,尽管 Java 程序结束的消息在 JMS 启动时被持久化并可用(这次是由消费者)
在第二种情况下,模式不是持久的。因此,程序一结束,消息就消失了。