需在獨立 Java 客戶端通過 JNDI 獲取 GlassFish 中配置的 ConnectionFactory 與 Queue 進行 JMS 測試,避免引入額外 Broker。
jms/MyConnectionFactory (類型 javax.jms.QueueConnectionFactory)jms/MyQueue (類型 javax.jms.Queue)從 $GLASSFISH_HOME/lib 複製:
appserv-rt.jarjavaee.jarappserv-deployment-client.jarappserv-ext.jarappserv-admin.jarimqjmsra.jar (JMS 提供者)// 預設 InitialContext 自動讀取 classpath 下的 jndi.properties
Context context = new InitialContext();
QueueConnectionFactory qcf = (QueueConnectionFactory) context.lookup("jms/MyConnectionFactory");
Queue queue = (Queue) context.lookup("jms/MyQueue");
// 後續標準 JMS 流程
QueueConnection conn = qcf.createQueueConnection();
QueueSession session = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
QueueSender sender = session.createSender(queue);
TextMessage msg = session.createTextMessage("Hello GlassFish JMS");
sender.send(msg);
關鍵點:無需額外 Properties,appserv-rt.jar 內置 jndi.properties 指向 GlassFish 預設命名服務。
若需查找遠程 EJB,必須顯式配置 CORBA 通訊參數:
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
props.setProperty("org.omg.CORBA.ORBInitialPort", "3700"); // GlassFish 預設 IIOP 埠
Context context = new InitialContext(props);
MyRemote ejb = (MyRemote) context.lookup("ejb/MyRemote");
InitialContext,極簡配置