什么是JMS中的队列

时间:2015-11-06 09:31:59

标签: java jms

我有一项任务。在参数中是队列和消息。我必须将消息发送到队列。而且我的队列中没有这个队列。我认为那是目的地队列?非常感谢。

public class Producer {
    public static void main(String[] args) {
        try {
            // Получает контекст JNDI
            Context jndiContext = new InitialContext();
            // Выполняет поиск администрируемых объектов
            ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee7/ConnectionFactory" );
            Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue");
            //Создает необходимые артефакты для соединения с очередью
            Connection connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(queue);
            // Отправляет текстовое сообщение в очередь
            TextMessage message = session.createTextMessage("Сообщение отправлено " + new Date());
            producer.send(message);
            connection.close();
        } catch (NamingException | JMSException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我不确定你的问题,但JMS中的队列是一个点对点的临时区域。它确保消息只处理一次,但不保证订单处理。

如果您的示例是在向队列Queue发送短信,但您应该这样做:

connection.start()

开始你的连接。

现在,如果您想收到消息,可以这样做:

Context context = null;
ConnectionFactory factory = null;
Connection connection = null;
Destination destination = null;
Session session = null;
MessageConsumer receiver = null;

try {
  context = new InitialContext();
  factory = (ConnectionFactory) context.lookup("jms/javaee7/ConnectionFactory");
  destination = (Destination) context.lookup("jms/javaee7/Queue");
  connection = factory.createConnection();
  session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  receiver = session.createConsumer(destination);
  connection.start();

    Message message = receiver.receive();
    if (message instanceof TextMessage) {
      TextMessage text = (TextMessage) message;
      System.out.println("received message= " + text.getText());
    } else if (message != null) {
      System.out.println("No message in queue");
    }
} catch (Exception e) {
  e.printStackTrace();
} finally {
  if (context != null) {
    try {
      context.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }

  if (connection != null) {
    try {
      connection.close();
    } catch (JMSException e) {
      e.printStackTrace();
    }
  }
}
}

顺便说一句,如果你使用的是java 7,你应该使用 try-with-resources Statement