Spring Framework provides two common ways to empower enterprise applications such as message queues and email sending.
Message queues allow asynchronous communication between programs or systems. Not only allow you to send messages but object instances.
To integrate this technology in our applications a message queuing server like Apache ActiveMQ is required. Here you can download it: http://activemq.apache.org/activemq-5111-release.html
After unzipping the zip file, you will need to launch activemq.bat, placed into the bin directory and depending on the system in win64 or win32. Notice that various ports for a different range of technologies have been opened (websockets, stomp, etc)
One of the services that we may be interested in monitoring would be available at the url: http://localhost:8161
The default access to manage ActiveBroker works with admin/admin credentials, which will lead to a panel where you can view the active queues and messages exchanged, but for now it is still empty.
The project I’m going to focus on (please find this on my Bitbucket account), simulates a typical restaurant to generate a specific order to be sent later to the message queueing service. Notice that after reading and processing each order, an email will be sent.
The project consists of the following components:
• Order.java: a POJO representing an order.
• MessageSender.java: this class involves a run method with an infinite loop to generate instances of every single order sent to the queue.
• MessageReceiver.java: this class receives the orders.
• Main.java: the class with the main method that starts the MessageSender and MessageReceiver as well.
The beans file of the Spring Framework plays a pretty crucial role in the project. Besides preparing the bean to use ActiveMQ indicating all the required settings, you must inject the MessageSender and MessageReceiver beans. In turn, to make MessageReceiver able to send an email notification, it is necessary to inject the Emailer we have previously developed in another Spring Maven project for that purpose.
As you can see, we must declare the message queue that will be used in our application:
Additionally we should note that we will also use the beans declared in the SpringMailer project. In this way we can reuse the established configuration.
We may also use the Jar generated in the previous project, just referring to Maven artifact through its coordinates in our pom.xml file:
Once we launch the class containing the main method, the system boots and starts the instances MessageSender. We can see the stack trace on the IDE console:
An email is sent just after every order received, so check your inbox ;-). Furthermore, we can see how many messages are sent and received through the ActiveMQ interface:
If you need further information take a look to my slides: