我想使用JMS Queue在独立应用程序中创建一个Message队列。我没有使用任何类型的容器,如tomcat和JBoss。传递给初始上下文对象的参数应该是什么?它完全是一个独立的应用程序..
注意:如果有人希望对这个问题进行投票,请在评论中说出原因并放弃投票。谢谢!
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();
答案 0 :(得分: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