Search code examples
javaspringapache-camelactivemq-artemis

org.springframework.jms.connection.CachingConnectionFactory provide username and password


How do I provide a username and password into a org.springframework.jms.connection.CachingConnectionFactory? (NOT the rabbit one).

Using Apache Camel, I'm trying the following:

ActiveMQComponent amqComponent = new ActiveMQComponent();
//amqComponent.setUsername(amqUser);
//amqComponent.setPassword(amqPassword);
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
cf.setBrokerURL("tcp://" + amqServer + ":" + amqPort + "?jms.watchTopicAdvisories=false");

CachingConnectionFactory ccf = new CachingConnectionFactory(cf);
ccf.setClientId("clientID");
amqComponent.setConnectionFactory(ccf);

context.addComponent("activemq", amqComponent);

If I uncomment the .setUsername and .setPassword calls, I get an error:

"SingleConnectionFactory does not support custom username and password"

(because SingleConnectionFactory is the parent class for this CachingConnectionFactory).

Clearly if I leave the lines commented, I get an authentication error because I'm not providing a user/password.

How can I pass the ActiveMQ credentials when using a CachingConnectionFactory?

(as an aside, Spring Integration: How to use SingleConnectionFactory with ActiveMQ? discusses why I am trying to use a CCF as opposed to just using the ActiveMQConnectionFactory - "with each poll, it creates a new connection to the Broker - flooding my broker with hundreds of connections")


Solution

  • You need to use a UserCredentialsConnectionFactoryAdaptor, e.g. as follows:

    ActiveMQComponent amqComponent = new ActiveMQComponent();
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
    cf.setBrokerURL("tcp://" + amqServer + ":" + amqPort + " jms.watchTopicAdvisories=false");
           
    UserCredentialsConnectionFactoryAdapter uca = new UserCredentialsConnectionFactoryAdapter();
    uca.setUsername(amqUser);
    uca.setPassword(amqPassword);
    uca.setTargetConnectionFactory(cf);
                
    CachingConnectionFactory ccf = new CachingConnectionFactory(uca);
    ccf.setClientId(amqClientID);
                
    amqComponent.setConnectionFactory(ccf);
    amqComponent.setMaxConcurrentConsumers(1);
                
    context.addComponent("activemq", amqComponent);