如何在 JMS 中初始化初始上下文

How to initialize initial context in JMS

我想使用 JMS 队列在独立应用程序中创建消息队列。我没有使用任何类型的容器,如 tomcat 和 JBoss。传递给初始上下文对象的参数应该是什么?它完全是一个独立的应用程序..

注意:如果有人希望对该问题投反对票,请在评论中说明理由并投反对票。谢谢!

       InitialContext ctx = new InitialContext(?????);
       Queue queue = (Queue) ctx.lookup("queue/queue1");
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup("queue/connectionFactory");
       QueueConnection queueConn = connFactory.createQueueConnection();
       QueueSession queueSession = queueConn.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
       QueueSender queueSender = queueSession.createSender(queue);
       queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
       TextMessage message = queueSession.createTextMessage("Hello");
       queueSender.send(message);
       System.out.println("sent: " + message.getText());
       queueConn.close();

您无法通过 jndi 解析 connectionFactory,因为没有容器提供它。

您必须自己实例化 connectionFactory,提供必要的(传输)参数。

由于您不从 Java EE 容器中检索它,因此相关的 JSR 未涵盖此行为,因此特定于提供者。

下面是一个使用 HornetQ 的例子:

// Transport parameters
final Map< String, Object > connectionParams = new HashMap< String, Object >();
connectionParams.put(TransportConstants.PORT_PROP_NAME, port);
connectionParams.put(TransportConstants.HOST_PROP_NAME, host);

final TransportConfiguration transportConfiguration = new TransportConfiguration(
    NettyConnectorFactory.class.getName(), connectionParams);

// this should be created only once and reused for the whole app lifecycle
connectionFactory = (ConnectionFactory) org.hornetq.api.jms.HornetQJMSClient
    .createConnectionFactoryWithoutHA(JMSFactoryType.QUEUE_CF, transportConfiguration);

final jmsQueue = HornetQJMSClient.createQueue(queueName)   

try {
    // connection is thread safe
    Connection connection = null;

    // session is not
    Session session = null;

    connection = connectionFactory.createConnection(user, password);
    connection.start();

   /* following objects must be propper to a thread (but should be reused if possible) */

    // Create a non transacted Session (no XA support outside of Java EE container)
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final MessageProducer producer = session.createProducer(jmsQueue);
    final ObjectMessage objectMessage = session.createObjectMessage();

    objectMessage.setObject(myMessageSerializableObject);

    producer.send(objectMessage);
}
finally {
    // Release resources
    try {
        if (session != null) {
          session.close();
        }
        if (connection != null) {
          connection.close();
        }
    }
    catch (final JMSException e) {
        LOG.warn("An error occurs while releasing JMS resources", e);
    }
}

请注意,连接、会话和生产者应该被重用(不是为每次使用创建和释放但不是在线程之间共享)并且最好是合并。

https://developer.jboss.org/wiki/ShouldICacheJMSConnectionsAndJMSSessions