無法通過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
來源
2015-07-02 15:00:41
Gab
這取決於從JMS提供者,但如果你不使用容器,那麼通常你必須使用供應商相關的類和API來訪問消息提供者。 – Gas