我可以从应用服务器外部向JMS队列发送消息吗?

Sim*_*son 7 java jms java-ee

据我了解,J2EE容器需要包含JMS提供程序.独立Java应用程序是否可以将消息发送到容器提供的JMS队列?如果是这样,我如何从容器外部访问JNDI查找?

(我正在尝试使用Geronimo,如果它有任何区别,但我希望有一种标准的方法来做到这一点.)

pjp*_*pjp 5

您应该能够创建一个在Geronimo 中使用JNDI服务器的InitialContext.然后,您可以使用它来查找JMS连接工厂和队列.

以下示例改编自http://forums.sun.com/thread.jspa?threadID=5283256以使用Geronimo JNDI Factory.

Context                  jndiContext = null;
ConnectionFactory   connectionFactory = null;
Connection             connection = null;
Session                  session = null;
Queue                    queue = null;
MessageProducer     messageProducer = null;   

try
{
    //[1] Create a JNDI API InitialContext object.
    Hashtable properties = new Hashtable(2);

    // CHANGE these to match Geronimos JNDI service

    properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
    properties.put(Context.PROVIDER_URL, "ejbd://127.0.0.1:4201");
    jndiContext = new InitialContext(properties);

    //[2] Look up connection factory and queue.
    connectionFactory = (ConnectionFactory)jndiContext.lookup("jms/ConnectionFactory");
    queue = (Queue)jndiContext.lookup("jms/Queue");

    //[3]
    // - Create connection
    // - Create session from connection; false means session is not transacted.
    // - Create sender and text message.
    // - Send messages, varying text slightly.
    connection = connectionFactory.createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    messageProducer = session.createProducer(queue);

   //send a message
   TextMessage message = session.createTextMessage(this.jTextSend.getText()); 
   messageProducer.send(message); 

   //example for send some object
   //ObjectMessage message = session.createObjectMessage();
   //MyObj myObj = new MyObj ("Name"); //this class must be serializable 
   //message.setObject(myObj );
   //messageProducer.send(message);
}
catch(Exception ex)
{
   LOG.error(ex);
}
finally
{
     if(connection !=null)
     {
         try
         {
             connection.close();
         }
         catch(JMSException e)
         {
              LOG.error(e);
         }
     }
}
Run Code Online (Sandbox Code Playgroud)