如何在JMS中使用用户名和密码进行连接?

huangapple go评论59阅读模式
英文:

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(以及其子类,如QueueConnectionFactoryTopicConnectionFactory)具有使用用户名和密码创建ConnectionJMSContext的方法,例如:

在您的情况下,您可以使用类似以下的方法:

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.

huangapple
  • 本文由 发表于 2023年5月18日 02:21:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定