JMS or Java Messaging service is a solution for asynchronous communication using messages (objects). Initially, it was part of JSR (specification used in Java EE).
Let’s assume we have any service that can process only 100 requests per second. Any higher load will freeze service or put it down.
Such problems are very known and can be easily sorted by splitting API into two parts:
So the key thing in our problem is how to share information between 2 API? We might use a database or some Java collection, but JMS provides 2 convenient asynchronous solutions.
In Jms there are two main patterns: Queue and Topic. The key difference is that in Topic we can have many subscribers. Both structures can receive data from many producers.
There are many known Message Brokers like RabbitMq, Kafka, etc. In our example, we use a free open-source Active MQ broker. In order to install it do the next steps:
1. Download ActiveMQ Classic.
2. Install Java and add JAVA_HOME to PATH.
3. Execute wrapper.exe in apache-activemq-5.16.2\bin\win64.
5. Create Queue in tab Queues by pressing the Create button.
6. Add dependency in your Java application: XML1
The key profit we gain from Queue – load balancing in our application. Application won’t have more load than we can handle. We create threads – consumers that poll new users to be created and execute slow creation process (slow initialization isn’t necessary for this example but it emphasizes that the consuming process can easily break the application if expose outside). Once a user is created we store them in User Map. The diagram below describes design only with two consumers but can be easily scaled and for any given requirements (i.e., 200 user requests) and 2 seconds delay, we would create 100 consumers (producers can be also numbered but it’s not critical as far as pushing process cost nothing).
Initializing connectivity with ActiveMQ:
Pushing new user to ActiveMQ Queue:
Polling new user from ActiveMQ Queue and processing it:
Exposing API to be polled from the client-side:
Checking Active MQ Activity
In this implementation, we poll data from the queue without considering its processing status on the application side. So if we fail to create a user then the queue won’t be notified about it. To avoid it we add delivery acknowledgment at the end of the user creation process. Having it ActiveMQ will release the message only if the message was delivered + processed. Otherwise, if we fail to process it, the message will stay in the queue unless someone processes it successfully.
Change acknowledgment mode while creating session:
Department of Information Technologies: https://www.ibu.edu.ba/department-of-information-technologies/