Embed ActiveMQ using Java Code

You can use embedded ActiveMQ which means you can create object of BrokerService and then use java code to configure it instead of regular approach of using activemq.xml file, i wanted to try that so i did create this sample application which you can download from here First create HelloEmbeddedBrokerService class like this, in this class i am just creating object of BrokerService, after that you can call methods to configure it and once your done call brokerService.start() to start the broker.

package com.webspherenotes.jms;

import org.apache.activemq.broker.BrokerService;

public class HelloEmbeddedBrokerService {

  public static void main(String[] args) {
    try {

      BrokerService brokerService = new BrokerService();
      brokerService.addConnector("tcp://localhost:61616");
      brokerService.start();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Then use the jndi.properties file like this to configure JNDI context for the JMS client code

java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
java.naming.provider.url = tcp://localhost:61616
java.naming.security.principal=system
java.naming.security.credentials=manager
connectionFactoryNames = QueueCF
queue.SampleQ = jms.SampleQ
This is how the code for the message publisher would look like, as you can see your client code does not care how the message broker is started.

package com.webspherenotes.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.apache.activemq.ActiveMQConnectionFactory;

public class HelloActiveMQPublisher {

  /**
   * @param args
   */
  public static void main(String[] args) throws Exception{
    InitialContext context = new InitialContext();
    ConnectionFactory connectionFactory = (ConnectionFactory)context.lookup("QueueCF");
    
    Connection connection = connectionFactory.createConnection();
      connection.start();
      
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      
      Queue queue = (Queue)context.lookup("SampleQ");
      
      MessageProducer messageProducer = session.createProducer(queue);
      
      TextMessage textMessage = session.createTextMessage();
      textMessage.setText("Lets see if i can send messages using Embedded Broker");
      
      messageProducer.send(textMessage);

      connection.close();
  }

}

No comments: