Sunday, 5 August 2018

ActiveMQ: Hello World Application

This is continuation to my previous post. If you are not set up ActiveMQ in the system, I would recommend you go through my previous post and set it up.

My ActiveMQ instance is running at http://127.0.0.1:5050

Below step-by-step explains how to define a JMS producer that send messages to ActiveMQ, and define a JMS receiver that receives messages from ActiveMQ.

Step 1: Create new maven project in Eclipse.

Step 2: Add below maven dependencies to the pom.xml.
                  <dependency>
                           <groupId>org.apache.activemq</groupId>
                           <artifactId>activemq-client</artifactId>
                           <version>5.15.3</version>
                  </dependency>

Step 3: Create new package ‘com.sample.producer’ and define the class JMSProducer.java like below.

JMSProducer.java
package com.sample.producer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class JMSProducer {
 private static final String JMS_PROVIDER_URL = "tcp://127.0.0.1:5050";
 private static final String QUEUE = "DEMO_QUEUE";

 public static void main(String[] args) throws JMSException {
  ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(JMS_PROVIDER_URL);
  Connection connection = connectionFactory.createConnection();
  connection.start();

  Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

  Destination destination = session.createQueue(QUEUE);

  MessageProducer producer = session.createProducer(destination);

  TextMessage message = session.createTextMessage("Hello, this is my first message.");

  producer.send(message);

  connection.close();
 }
}

As you see above snippet, I am connecting the url "tcp://127.0.0.1:5050",

ActiveMQ provides number of transport protocols to communicate with JMS provider.

You can get the information from {ACTIVE_MQ_INSTALL_DIR}/conf/activemq.xml file
 <transportConnectors>
            <!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
            <transportConnector name="openwire" uri="tcp://0.0.0.0:5050?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
        </transportConnectors>

Step 4: Create new package ‘com.sample.consumer’ and define a class JMSConsumer.java like below.

JMSConsumer.java
package com.sample.consumer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class JMSConsumer {
 private static final String JMS_PROVIDER_URL = "tcp://127.0.0.1:5050";
 private static final String QUEUE = "DEMO_QUEUE";

 public static void main(String args[]) throws JMSException {
  ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(JMS_PROVIDER_URL);
  Connection connection = connectionFactory.createConnection();
  connection.start();

  Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

  Destination destination = session.createQueue(QUEUE);

  MessageConsumer consumer = session.createConsumer(destination);

  Message message = consumer.receive();

  if (message instanceof TextMessage) {
   TextMessage textMessage = (TextMessage) message;
   System.out.println("Received message '" + textMessage.getText() + "'");
  }

  connection.close();
 }
}


Step 5: Run the application JMSProducer.java.

Open the url ‘http://127.0.0.1:8161/admin/queues.jsp’, you can able to see DEMO_QUEUE and one message is enqueued to it.


Step 6: Run ‘JMSConsumer’ application.

You can able to see below messages.
Received message 'Hello, this is my first message.'

Open the url ‘http://127.0.0.1:8161/admin/queues.jsp’, you can able to see DEMO_QUEUE is empty (Number Of Pending Messages 0).


That’s it, you are done with first application.



Previous                                                 Next                                                 Home

Saturday, 4 August 2018

Installing and setting up ActiveMQ

In this post, you are going to learn.
a.   Setting up ActiveMQ
b.   Running ActiveMQ instance
c.   Testing the Installation
AcvtieMQ requires Java 1.7 or higher. Make sure you installed and setup java environment in your system.

Below post helps you in setting up Java.

Make sure, you set the JAVA_HOME environment variable to the directory where the JRE is installed.

Setting up ActiveMQ
Download latest stable release of ActiveMQ from below location.

At the time of writing this tutorial ‘ActiveMQ 5.15.3’ is the stable one.

There are two kinds of executables available, one for windows and other for Linux systems.

Installing ActiveMQ in windows
Extract the downloaded zip file.

The extraction contains below kind of directory structure.




The bin directory contains executable of activeMq. Add the bin directory to the system path.

Add AciveMQ bin path to system path in windows.
Right click on my computer -> properties.




Click on ‘Advanced system settings’.



Go to Advanced tab and click on ‘Environment Variables’ button.


Go to ‘System variables’ section, select the variable ‘Path’ and click on Edit button.




Add ActiveMQ bin directory path there.

Installing ActiveMQ in Linux
It is same as windows, extract the downloaded binary and add the ActiveMQ bin directory path to system path.

Running ActiveMQ instance
Open command prompt (or) terminal, and run the command ‘activemq start’.

When I ran above command, I end up in below error.
Failed to bind to server socket: tcp://0.0.0.0:61616

It is because, the port 61616 is already is use by some other process. There are two options to solve this problem.
a.   Kill the process that is running on port 61616.
b.   Change the port number

I chose second option and change the port number to 5050.

How to change the port number?
Go to <ACTIVEMQ_INSTALL_DIRECTORY>/conf folder.

Open ‘activemq.xml’ file and search for the port 61616 and replace it with 5050.

<transportConnector name="openwire" uri="tcp://0.0.0.0:5050?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
       
Now rerun the command ‘activemq start’.

C:\Users\krishna\Documents\Study\Active MQ\ActiveMQ Working Dir>activemq start
Java Runtime: Oracle Corporation 1.8.0_102 C:\Program Files\Java\jdk1.8.0_102\jre
  Heap sizes: current=1005056k  free=989327k  max=1005056k
    JVM args: -Dcom.sun.management.jmxremote -Xms1G -Xmx1G -Djava.util.logging.config.file=logging.properties -Djava.security.auth.login.config=C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\conf\login.config -Dactivemq.classpath=C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\conf;C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\../conf;C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\../conf; -Dactivemq.home=C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\.. -Dactivemq.base=C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\.. -Dactivemq.conf=C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\conf -Dactivemq.data=C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\data -Djava.io.tmpdir=C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\data\tmp
Extensions classpath:
  [C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\lib,C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\lib\camel,C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\lib\optional,C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\lib\web,C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\lib\extra]
ACTIVEMQ_HOME: C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..
ACTIVEMQ_BASE: C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..
ACTIVEMQ_CONF: C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\conf
ACTIVEMQ_DATA: C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\data
Loading message broker from: xbean:activemq.xml
 INFO | Refreshing org.apache.activemq.xbean.XBeanBrokerFactory$1@4cc0edeb: startup date [Sun Apr 22 00:48:39 IST 2018]; root of context hierarchy
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\data\kahadb]
 INFO | KahaDB is version 6
 INFO | PListStore:[C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\data\localhost\tmp_storage] started
 INFO | Apache ActiveMQ 5.15.3 (localhost, ID:INLN50911363A-51025-1524338320986-0:1) is starting
 INFO | Listening for connections at: tcp://INLN50911363A:5050?maximumConnections=1000&wireFormat.maxFrameSize=104857600
 INFO | Connector openwire started
 INFO | Listening for connections at: amqp://INLN50911363A:5672?maximumConnections=1000&wireFormat.maxFrameSize=104857600
 INFO | Connector amqp started
 INFO | Listening for connections at: stomp://INLN50911363A:61613?maximumConnections=1000&wireFormat.maxFrameSize=104857600
 INFO | Connector stomp started
 INFO | Listening for connections at: mqtt://INLN50911363A:1883?maximumConnections=1000&wireFormat.maxFrameSize=104857600
 INFO | Connector mqtt started
 WARN | ServletContext@o.e.j.s.ServletContextHandler@282cb7c7{/,null,STARTING} has uncovered http methods for path: /
 INFO | Listening for connections at ws://INLN50911363A:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600
 INFO | Connector ws started
 INFO | Apache ActiveMQ 5.15.3 (localhost, ID:INLN50911363A-51025-1524338320986-0:1) started
 INFO | For help or more information please see: http://activemq.apache.org
 WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\data\kahadb only has 43265 mb of usable space. - resetting to maximum available disk space: 43265 mb
 WARN | Temporary Store limit is 51200 mb (current store usage is 0 mb). The data directory: C:\Users\krishna\Documents\Study\Active MQ\softwares\apache-activemq-5.15.3-bin\apache-activemq-5.15.3\bin\..\data only has 43265 mb of usable space. - resetting to maximum available disk space: 43265 mb
 INFO | No Spring WebApplicationInitializer types detected on classpath
 INFO | ActiveMQ WebConsole available at http://0.0.0.0:8161/
 INFO | ActiveMQ Jolokia REST API available at http://0.0.0.0:8161/api/jolokia/
 INFO | Initializing Spring FrameworkServlet 'dispatcher'
 INFO | No Spring WebApplicationInitializer types detected on classpath
 INFO | jolokia-agent: Using policy access restrictor classpath:/jolokia-access.xml

Testing the Installation
Open the administrative interface by firing the URL:
Login: admin
Password: admin


Give the username and password as ‘admin’ and click on OK button.

You can able to see below kind of window.


Navigate to Queues.


Add a queue name ‘Hello World’ and click create.



“Hello World’ queue will be created.


Send test message by clicking on "Send to"




Add some message body. For example, I added ‘First Message sending to ActiveMQ queue’ and click on ‘Send’ button.


Now, you can able to see ‘Number Of Pending Messages’ as 1.





That’s it, your ActiveMQ setup is working perfectly….:)

Previous                                                 Next                                                 Home

Features of ActiveMQ

ActiveMQ is JSM compliant: ActiveMQ implements JMS 1.1 specification.

ActiveMQ supports number of languages
·       .NET
·       C (defunct)
·       C++
·       Erlang
·       Go
·       Haskell
·       Haxe (defunct)
·       Jekejeke Prolog
·       NetLogo
·       Node.js
·       Perl 5
·       Pike
·       Python
·       Racket
·       Ruby on Rails
·       Tcl/Tk

ActiveMQ support wide variety of protocols like SSl, TCP, UDP, AMQP, MQTT, OpenWire and STOMP.

ActiveMq support persistence using JDBC along with a high-performance journal.

ActiveMQ supports pluggable security through various different providers like JAAS.

ActiveMQ can be integrated with application servers Apache Tomcat, Jetty, Apache Geronimo, and JBoss.

ActiveMQ support clustering: You can cluster many ActiveMQ message brokers to achieve high availability.

Supports many advanced features such as Message Groups, Virtual Destinations, Wildcards and Composite Destinations

You can easily embed ActiveMQ in spring applications.

ActiveMQ support REST and WebSockets

Producers can send message to ActiveMQ and forget, ActiveMQ delivers the messages to the consumers on behalf of producers.




Previous                                                 Next                                                 Home

Introduction to ActiveMQ


ActiveMQ is an open source message broker that implements JMS specification.

What is Message Broker?
Message brokers receive messages from publishers and route them to consumers.

Is ActiveMQ implements JMS specification?
Yes

What are other products that implements JMS specification?
There are multiple products that implement JMS specification.

·       Amazon SQS with Java Messaging Library
·       Apache ActiveMQ
·       Apache Qpid
·       Oracle Weblogic
·       EMS from TIBCO
·       FFMQ, GNU LGPL licensed
·       FioranoMQ
·       IBM MQ
·       JBoss Messaging and HornetQ from JBoss
·       JORAM, from the OW2 Consortium
·       Lightstreamer JMS Extender
·       Open Message Queue, from Oracle
·       OpenJMS, from The OpenJMS Group
·       RabbitMQ, from Pivotal (JMS Client for RabbitMQ)
·       Solace JMS from Solace Systems
·       SAP NetWeaver Process Integration
·       SonicMQ from Aurea Software
·       SwiftMQ
·       Tervela
·       Ultra Messaging
·       webMethods from Software AG
·       WebSphere Application Server from IBM

Even though ActiveMQ implements JMS specification, apart from this, it provides more features. For example, it support REST, WebSocket interfaces.

What is the latest version of ActiveMQ?
At the time of writing this tutorial ‘5.15.3’ is the latest verison, released in Jan 2018.

Is ActiveMQ written in Java?
Yes

What are the protocols supported by ActiveMQ?
AMQP, MQTT, OpenWire and STOMP

Is ActiveMQ Support languages other than java?
Yes, at the time of writing this tutorial, ActiveMQ supports below languages.

·       .NET
·       C (defunct)
·       C++
·       Erlang
·       Go
·       Haskell
·       Haxe (defunct)
·       Jekejeke Prolog
·       NetLogo
·       Node.js
·       Perl 5
·       Pike
·       Python
·       Racket
·       Ruby on Rails
·       Tcl/Tk

What is Asynchronous Messaging?
In MOM (Message oriented Middleware) model, senders send the messages to message brokers like Apache ActiveMQ, and receiver receive the messages from ActiveMQ. There is no direct contact between sender and receiver. Senders do not have any idea about receivers and Receivers do not have any idea about senders. This is called Asynchronous Messaging.

Terminology
Message Broker: Message brokers receive messages from publishers and route them to consumers.

Exchange: Messages are published to exchanges. Exchanges distribute message copies to queues using rules called bindings.

Producer: Program that sends messages is called a producer.

Queue: Whatever the messages sent by producers to ActiveMQ are stored in queues. Theoretically queue is infinite size buffer, producers can send as many messages as they want. Many producers can send messages that go to one queue. Many consumers can try to receive data from one queue.

Consumer: It is a program that receives messages from queue and processes them.

JMS Client: It is an application that can send / receive messages from JMS provider.  

JMS Producer: An application that sends messages to JMS provider

JMS Consumer: An application that receives messages from JMS provider

JMS Provider:  An application that implements JMS specification. Ex: Active MQ, Rabbit MQ etc.,

JMS Message: It is the basic construct, used by JMS client, Receiver to send and receive messages. You can send any information as part of jms message including text, binary, headers.

I am using below maven dependency throughout the tutorial.

                  <dependency>
                           <groupId>org.apache.activemq</groupId>
                           <artifactId>activemq-client</artifactId>
                           <version>5.15.3</version>
                  </dependency>




Previous                                                 Next                                                 Home

ActiveMQ Tutorial

Introduction to ActiveMQ
Features of ActiveMQ
Installing and setting up ActiveMQ
ActiveMQ: Hello World Application
ActiveMQ: Delete a queue programmatically in Java
Introduction To JMS
JMS Domains
JMS Features
JMS Messages
JMS: Headers
JMS: Why should I disable message ID?
JMS: Working with JMSTimestamp
JMS: When Can I use JMSCorrelationID?
JMS: setJMSReplyTo: Send message reply
JMS: JMSType: set jms type of message
JMS: JMSExpiration: Set the expiration of the message
JMS: JMSPriority: Set priority to the jms message
JMS: Message properties
JMS defined properties
JMS properties supported by ActiveMq
JMS: Provider specific properties
JMS: Message interface
JMS: Message Selectors
JMS: Message Selectors in detail
JMS: Message body
JMS: MessageNotWriteableException
Exploring JMS point-to-point model
JMS: Temporary Queue
JMS: Queue Browser: Get all the items in a queue
JMS: Queue browser: filter the messages
JMS publish/subscribe model
JMS: Temporary Topics

Previous                                                 Next                                                 Home