2015-07-02 57 views
1

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

注意:如果有人希望放弃对这个问题的投票,请在评论中给出原因并放弃投票。谢谢!

 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(); 
+1

这取决于从JMS提供者,但如果你不使用容器,那么通常你必须使用供应商相关的类和API来访问消息提供者。 – Gas

回答

2

无法通过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

+0

谢谢@加布。你的解释对我来说非常有用。获得你的学分。 – Kaliappan