Reputation: 3186
I'm trying to write a simple java code that connects to activeMQ queue, I found this resource online which basically follow the Hello World example in activeMQ site. I'm trying to specify username and password alongside a queue name and I'm unable to find any helpful resource online, so any help would be highly appreciated.
I made the following changes in the producer code and I'm not sure how to specify factory name and if I'm specifying username and password correctly?
// First create a connection
InitialContext initCtx = new InitialContext();
javax.jms.ConnectionFactory qcf = (javax.jms.ConnectionFactory) initCtx.lookup(factoryName);
Connection connection = qcf.createConnection("admin","admin");
connection.start();
Upvotes: 1
Views: 1803
Reputation: 3913
here is an example
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL,
"tcp://localhost:61616");
props.put("topic." + "TOPICNAME", "TOPICNAME");
InitialContext ic = new InitialContext(props);
ConnectionFactory cf1 = (ConnectionFactory) ic.lookup("ConnectionFactory");
writeDestination = (Topic) ic.lookup("TOPICNAME");
writeDestConnection = cf1.createConnection("user", "pwd");
writeDestConnection.setClientID("durableSubscriber_" + "TOPICNAME");
writeDestSession = writeDestConnection.createSession(false,Session.AUTO_ACKNOWLEDGE);
writeDestProducer = writeDestSession.createProducer(writeDestination);
writeDestConnection.start();
TextMessage message = writeDestSession.createTextMessage(json);
message.setStringProperty("clientID", "ifYouNeed");
writeDestProducer.send(message);
http://activemq.apache.org/jndi-support.html
here is another example without jndi:
public static void main(String[] args) throws JMSException {
Connection conn = null;
try {
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
conn = cf.createConnection("user", "pwd");
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createQueue("queueName"));
conn.start();
TextMessage msg = null;
while ((msg = (TextMessage) consumer.receive()) != null) {
System.out.println("Received message is: " + msg.getText());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
}
Upvotes: 1