这是一个老话题,但也许它可以提供帮助。
要将消息发送到 JMS 队列实际上需要以下内容:
Context context = null;
QueueConnection queueConnection = null;
QueueSession queueSession = null;
Queue queue;
这就是它的工作原理:
context = getContext(host, port, user, password);
queueConnection = getConnectionFactory(context, connectionFactoryJndi);
queueSession = getQueueSession(queueConnection);
queue = getQueue(context, queueJndi);
// send a text message
queueConnection.start();
String message = "hello";
sendMessageToQueue(verbose, message, queueSession, queue);
queueConnection.stop();
要获取你需要连接到服务器的上下文:
private Context getContext(String host, int port, String user, String password) throws NamingException {
String url = String.format("%s://%s:%d", protocol, host, port);
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_PRINCIPAL, user);
env.put(Context.SECURITY_CREDENTIALS, password);
return new InitialContext(env);
}
获取连接工厂:
private QueueConnection getConnectionFactory(Context context, String jndiName)
throws NamingException, JMSException {
QueueConnectionFactory connectionFactory = (QueueConnectionFactory) context.lookup(jndiName);
return connectionFactory.createQueueConnection();
}
打开一个队列会话:
private QueueSession getQueueSession(QueueConnection queueConnection) throws JMSException {
return queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
}
获取队列:
private Queue getQueue(Context context, String jndiName) throws NamingException {
return (Queue) context.lookup(jndiName);
}
最后,将您的消息发送到队列:
私有静态 void sendMessageToQueue(boolean verbose,
字符串消息,
队列会话队列会话,
队列队列)抛出 JMSException {
TextMessage textMessage = queueSession.createTextMessage(message);
try (QueueSender queueSender = queueSession.createSender(queue)) {
queueSender.send(textMessage);
}
}
这些代码 sn-ps 来自这里:https://github.com/zappee/jms-message-sender
这是一个JMS sender命令行工具,可以以本项目为例。
希望对你有帮助。