英文:
How to connect by user/password in JMS?
问题
我有一个连接到经纪人的代码,通过URL连接。我不明白如何通过登录/密码也进行连接?
public static QueueSession getQueueSession(String urlBroker) throws JMSException {
QueueConnectionFactory connectionFactory = new ActiveMQQueueConnectionFactory("tcp://" + urlBroker);
QueueConnection connection = connectionFactory.createQueueConnection();
return connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
}
英文:
I have a code that connects to a broker by url. I do not understand how to make connections also by login / password?
public static QueueSession getQueueSession(String urlBroker) throws JMSException {
QueueConnectionFactory connectionFactory = new ActiveMQQueueConnectionFactory("tcp://" + urlBroker);
QueueConnection connection = connectionFactory.createQueueConnection();
return connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
}
答案1
得分: 2
ConnectionFactory
(以及其子类,如QueueConnectionFactory
和TopicConnectionFactory
)具有使用用户名和密码创建Connection
或JMSContext
的方法,例如:
在您的情况下,您可以使用类似以下的方法:
public static QueueSession getQueueSession(String urlBroker, String username, String password) throws JMSException {
QueueConnectionFactory connectionFactory = new ActiveMQQueueConnectionFactory("tcp://" + urlBroker);
QueueConnection connection = connectionFactory.createQueueConnection(username, password);
return connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
}
值得注意的是,此方法存在一个相当严重的错误,因为它每次调用时都会泄漏一个QueueConnection
实例。像这样的连接需要小心管理。请不要丢失对此实例的引用,以便稍后在使用完后关闭它。否则,您将浪费代理程序的资源,可能会降低性能并阻止其他客户端连接。
英文:
The ConnectionFactory
(and its sub-classes like QueueConnectionFactory
and TopicConnectionFactory
) has methods to create a Connection
or JMSContext
using username & password, e.g.:
In your case you could use something like:
public static QueueSession getQueueSession(String urlBroker, String username, String password) throws JMSException {
QueueConnectionFactory connectionFactory = new ActiveMQQueueConnectionFactory("tcp://" + urlBroker);
QueueConnection connection = connectionFactory.createQueueConnection(username, password);
return connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
}
It's worth noting that this method has a fairly serious bug because it is leaking a QueueConnection
instance every time it's invoked. A connection like this is important to manage carefully. Please don't lose the reference to this instance so you can close it later when you're done with it. Otherwise you're going to waste resources on the broker potentially degrading performance and preventing other clients from connecting.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论