2015-07-02 55 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