代码之家  ›  专栏  ›  技术社区  ›  user3198603

是否在JMS队列上发布消息?

  •  1
  • user3198603  · 技术社区  · 11 年前

    我是JMS的新手,并通过以下示例 Active MQ Hello world 。假设我每次进入都有一个场景 在DB中的employee表下,我必须将消息放入队列中。下面是helloworld示例中的生产者代码片段

    public static class HelloWorldProducer  {
            public void createMessageOnQueue() {
                try {
                    // Create a ConnectionFactory
                    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
    
                    // Create a Connection
                    Connection connection = connectionFactory.createConnection();
                    connection.start();
    
                    // Create a Session
                    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    
                    // Create the destination (Topic or Queue)
                    Destination destination = session.createQueue("TEST.FOO");
    
                    // Create a MessageProducer from the Session to the Topic or Queue
                    MessageProducer producer = session.createProducer(destination);
                    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    
                    // Create a messages
                    String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode();
                    TextMessage message = session.createTextMessage(text);
    
                    // Tell the producer to send the message
                    System.out.println("Sent message: "+ message.hashCode() + " : " + Thread.currentThread().getName());
                    producer.send(message);
    
                    // Clean up
                    session.close();
                    connection.close();
                }
                catch (Exception e) {
                    System.out.println("Caught: " + e);
                    e.printStackTrace();
                }
            }
        }
    

    现在我的问题是,如果我关闭连接和会话,它是否也会关闭队列?如果是,如果消息尚未被消费,会发生什么?

    第二个问题是,如果我需要第二次在同一队列(即“TEST.FOO”)上发布消息,我需要调用 createMessageOnQueue 方法第二次。如果是,它是否不会使用 session.createQueue("TEST.FOO")?

    2 回复  |  直到 11 年前
        1
  •  0
  •   Amit G    11 年前

    现在我的问题是,如果我关闭连接和会话,会吗 还要关闭队列吗?如果是,如果消息未被 消费了吗?

    消息仍将在队列中。没有“关闭队列”之类的事情。

    第二个问题是我是否需要在同一队列上发布消息(即 “TEST.FOO”)第二次,我需要调用createMessageOnQueue吗 方法第二次。如果是,它是否不会使用 session.createQueue(“TEST.FOO”)?

    session.createQueue(“TEST.FOO”)不一定创建队列,它只是获取对现有队列的引用。

    会话#createQueue()的javadoc

    注意,此方法只创建一个对象,该对象封装 主题的名称。它不会在JMS中创建物理主题 供应商。JMS不提供创建物理主题的方法, 因为这将特定于给定的JMS提供者。创建 物理主题是特定于提供者的,通常是管理性的 由管理员执行的任务,尽管某些提供程序可能会创建 在需要时自动进行。

        2
  •  0
  •   coyote    11 年前

    队列创建一次,只有您可以手动删除它。 消息发送到队列后,它将在队列上等待,直到其被使用(与主题不同)。

    如果要发送两次,则不需要重新创建邮件。但话说回来,你为什么要寄两次?

    我觉得可以使用JMS事务解决您的问题。