What is JMS?
The JMS, or Java Message Service API, is a messaging standard that allows us to send and receive messages between two or more clients (applications).
Why JMS?
We can send and receive messages using RESTful APIs, then why do we need JMS? Java Message Service offers distinct advantages over APIs. Let’s explore this with the following example:
Imagine a scenario in which a client needs to communicate with a server. Using RESTful APIs, the client needs to know the address of the server to send a request. This becomes more complex if there are multiple servers, as the client needs to manage and be aware of each of the servers. In contrast, JMS introduces a broker, which acts as a middleware between a client and a server. It also provides the following advantages:
- Decoupling
- Asynchronous Communication
- Scalability and load balancing
- Message durability and reliability
JMS Architecture: Java Message Service core components
Messaging Server (JMS Server)
A messaging server is the main component of the Java Message Service that facilitates the exchange of messages between producer and consumer. Messaging server has JMS Provider, Queue and Topic. It is used to manage the routing, delivery, and storage of messages. Example: JBoss Messaging Server.
JMS Providers
JMS providers are the implementation of the JMS API that is used to send and receive messages in a distributed system. It is mainly used for the routing and delivery of messages. JBoss supports JBossMQ as a JMS provider. There are various JMS providers available, such as ActiveMQ, JBossMQ, RabbitMQ, HornetQ, and IBM WebSphere MQ.
Producer or Publisher
The producer or publisher is used to create the message and send it to the queue or topic.
Receiver or Subscriber
The receiver or subscriber listens to the queue and the topic, and if messages are available in the queue or topic, it will consume the messages.
JMS Client
A JMS client is an application or component that produces (sends) or consumes (receives) messages using the JMS API. The JMS clients communicate with a JMS provider (messaging server) to perform messaging operations. A JMS client can be a producer, receiver or both at once.
Queue and Topic
In JMS, queue and topic are the two different destinations that are used for sending and receiving messages. They support two different messaging models: point-to-point and publish-subscribe, respectively.
JMS Message Types
We can send and receive various messages using the JMS API.
Message Type | Contains | Methods |
TextMessage | String | getText, setText |
MapMessage | set of key-value pair | setString, setDouble, setLong, getDouble, getString |
BytesMessage | stream of uninterpreted bytes | writeBytes, readBytes |
StreamMessage | stream of primitive values | writeString, writeDouble, writeLong, readString |
ObjectMessage | serialize object | setObject, getObject |