Oc-windows.ru

IT Новости из мира ПК
8 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java message service

JMS сообщения в Java приложении

JMS (Java Message Service) является стандартом обмена сообщениями между приложениями. Java приложения, выполненные по технологии Java SE (standalone) или Java EE (WEB) могут создавать, отправлять и получать JMS сообщения. Программное обеспечение, используемое для передачи сообщений между приложениями по стандарту JMS, формирует очереди сообщений queue.

Отправка сообщений java-приложениями выполняется в асинхронном режиме, т.е. процедура не ждет ответа от получателя. В качестве получателей сообщений, организующих очереди (queue), может быть либо программное обеспечение типа WebSphere MQ, связывающее приложения через канал обмена сообщениями, либо WEB-контейнер типа JBoss, GlassFish, обеспечивающих обмен сообщениями между приложениями контейнера, либо по каналам Интернета с использованием JNDI.

Получение сообщений java-приложением осуществляется либо по «подписке» (технология «издатель-подписчик»), либо из очереди («точка-точка»). Для получения сообщений по подписке необходимо должным образом подключиться к соответствующей очереди. При появлении в очереди сообщений они отправляются всем подписчикам. В модели «точка-точка» для получения сообщений необходимо периодически подключаться к соответствующей очереди и читать в ней сообщения.

В статье рассматриваются примеры отправки и получения сообщений с использованием как WEB-приложения (Java EE), так standalone приложения (Java SE). Описание примеров разделено на две части. На этой странице рассматривается взаимодействие WEB-приложения с провайдером HornetQ. Взаимодействие standalone Java приложения с Websphere MQ рассматривается здесь.

Пример обмена сообщения с сервером JBoss

В первом простейшем WEB-приложении «jms-jboss» для отправки и получения JMS сообщений в качестве контейнера будет использован сервер приложений Wildfly версии 8.2 (ранее JBoss Application Server или JBoss AS).

Настройка сервера приложений Wildfly

Чтобы использовать Wildfly для обмена сообщениями JMS необходимо настроить его файл конфигурации /standalone/configuration/standalone.xml. По умолчанию настройки JMS не включены в конфигурационный файл и их нужно определить вручную. Но можно использовать файл конфигурации standalone-full.xml, в котором сервер включает настройки JMS провайдера HornetQ, обеспечивающего создание соответствующих очередей и обмен сообщениями.

В файл конфигурации standalone-full.xml в раздел секции добавим очередь. Две очереди (ExpiryQueue и DLQ) уже имеются в подразделе . Добавим свою очередь testQueue с JNDI ‘jms/queue/test’ :

Для примера достаточно было добавить один элемент ‘ ‘, который работает внутри контейнера. Второй элемент «java:jboss/exported/jms/queue/test» может работать за пределами контейнера, т.е. из другой JVM. Для него обязательным условием является определение в начале наименования «java:jboss/exported/». Можно было бы конечно использовать и существующие очереди (ExpiryQueue и DLQ).

Примечание :
DLQ (Dead Letter Queue) – это локальная очередь, называемая инача как очередь недоставленных сообщений. Такую очередь создают для каждого менеджера очередей, чтобы отлавливать неотправленные сообщения, связанные с проблемами в сети или у получателя.

Если не создать DLQ, то ошибки в приложениях могут отключать каналы. В этом случае не только прекратится получение сообщений в очереди, но может нарушиться работа и провайдера MQ, к примеру, не будут получены и выполнены команды администратора. Рекомендуется проектировать приложения таким образом, чтобы избегать подобных сценариев. Кроме того, следует проводить мониторинг DLQ, поскольку поступающие в эту очередь сообщения чаще всего содержат ошибки.

Чтобы стартовать Wildfly с файлом конфигурации standalone-full.xml из IDE Eclipse необходимо открыть окно ‘JBoss Runtime’ и определить значение ‘Configuration file’. Для этого откройте вкладку Servers (Perspective ‘Java EE’) и дважды щелкните мышью на сервере Wildfly. В открывшемся окне Overview нажмите на ссылку ‘Runtime Enviroment’, в результате чего будет открыто окно ‘JBoss Runtime’ :

Для запуска сервера приложений Wildfly не из IDE Eclipse c конфигурационным файлом standalone-full.xml можно использовать командный файл, в котором определить файл в качестве параметра : ./standalone.sh -c standalone-full.xml

В конце страницы приведен Log сервера Wildfly, в котором показано создание соответствующих очередей и подключение MDB-объекта приложения к адаптеру HornetQ для получения JMS сообщений по подписке.

Описание примера

На следующем скриншоте приведена структура WEB-приложения jms-jboss, включающего :

  • ServiceServlet — сервлет, используемый для отправки и получения JMS сообщений;
  • Sender — отправитель JMS сообщений;
  • Receiver — MDB получатель JMS сообщений;
  • jquery-3.2.1.min.js — библиотека jQuery для асинхронных ajax-вызовов сервлета;
  • index.jsp — интерфейсная страница приложения.

Проект в среде IDE Eclipse с использованием maven представлен на следующем скриншоте.

Листинг сервлета ServiceServlet

Сервлет ServiceServlet вызывается со страницы index.jsp из браузера с использованием jQuery. В качестве параметров сервлет получает ‘prefix’ сообщения и команду ‘mode’. Для отправки JMS сообщения сервлет использует метод sendMessage класса Sender. Отправленные сообщения сервер Wildfly сразу же возвращает подписчику Receiver. Полученные сообщения сервлет читает из статической коллекции Receiver.messages, после чего очищает её.

Отправленные и полученные сообщения сервлет оформляет в виде HTML-кода и возвращает в браузер.

Листинг дескриптора приложения, web.xml

В дескрипторе приложения web.xml описывается сервлет ServiceServlet и его URL (url-pattern) для вызова, а также открываемая по умолчанию страница приложения.

Листинг класса отправителя сообщений Sender

Класс отправителя создается и «живет» вместе с WEB-приложением согласно аннотации @ApplicationScoped. При инсталляции сразу же определяются context и очередь queue. Сервлет отправляет текстовые сообщения, вызывая метод sendMessage.

Листинг получателя сообщений Receiver

Здесь следует несколько слов сказать о MDB (Message Driven Beans). Объект MDB используется для поддержки асинхронных коммуникаций в приложении, как правило, в сочетании с очередями. Клиент посылает сообщение в очередь, а MDB объект получает эти сообщения из очереди по подписке. Клиент не может вызывать MDB напрямую, связь обеспечивается с помощью сообщений JMS. MDB никогда не отвечает клиенту.

Класс получателя сообщений оформлен как MDB объект с использованием аннотации, в которой определен ряд параметров, включающий JNDI очереди ‘jms/queue/test’. Получатель реализует интерфейс javax.jms.MessageListener, согласно которому переопределяет метод onMessage.

При появлении в очереди ‘jms/queue/test’ сообщения сервер приложений Wildfly сразу же вызовет метод onMessage данного MDB-объекта и передаст ему в качестве параметра сообщение javax.jms.Message, текст которого будет сохранен в коллекции messages. Сервлет имеет прямой доступ к набору полученных сообщений messages с модификаторами public и static.

Листинг страницы index.jsp

На странице index.jsp определена библиотека jquery-3.2.1.min.js и JavaScript методы, которые используются для ajax-вызова сервлета. Интерфейс страницы включает текстовое поле ‘prefix’ и кнопки ‘Отправить’ и ‘Получить’.

Интерфейс страницы в браузере представлен на следующем скриншоте.

При нажатии на кнопку ‘Отправить’ вызывается JavaScript процедура sendMessages, определяющая значения параметров (mode, prefix) и вызывающая сервлет для отправки сообщений. Результат выполнения команды в виде набора сообщений, оформленных в HTML-коде, возвращается в функцию success, которая выкладывает его в поле sendJMS на странице. Если префикс не определен, то сервлет будет использовать по умолчанию значение ‘prefix’. Как только сообщения попадут в очередь сервер вернет их объекту ‘Receiver’ по подписке.

При нажатии на кнопку ‘Получить’ вызывается JavaScript процедура receiveMessages, определяющая значение параметры mode и вызывающая сервлет для чтения полученных по подписке сообщений. Результат выполнения команды в виде набора сообщений, оформленных в HTML-коде, возвращается в функцию success, которая выкладывает его в поле receiveJMS на странице.

Старт сервера Wildfly

Сервер приложений Wildfly «логирует» всю информацию. При старте из IDE Eclipse эта информация дополнительно выводится в консоль. Ниже представлена информация (в сокращенном виде), связанная с настройкой сервером JMS очередей и стартом приложения «jms-jboss». В предпоследней строке отображено подключение MDB (Message Driven Bean) ‘Receiver’ к провайдеру HornetQ.

Скачать пример

Исходный код рассмотренного примера в виде проекта Eclipse с использованием Maven можно скачать здесь (994 Кб).

Примеры взаимодействия Java приложения c Websphere MQ по отправки и чтению JMS сообщений представлены здесь.

JMS Tutorial – Java Message Service Tutorial

By Lokesh Gupta | Filed Under: JMS

Java Message Service is an API which supports the formal communication called as messaging between computers on a network. It provides a common interface for standard message protocols and message services in support to the Java programs. It provides facility to create, send and read messages. The JMS API reduces the concepts that a programmer must learn to use the messaging services/products and it also provides the features that support the messaging applications.
JMS is a technique which is used in J2EE technology for an application to communicate with the other application in loosely coupled manner. It means that the applications which have to communicate are not connected directly they are connected through a common destination. We will go in detail later in this jms tutorial.

Читать еще:  Не печатает принтер пишет ошибка печати

1. JMS Tutorial – Need of JMS

In Java, if a person wants to send a message from one application to another in such a way that both application do not know anything about each other, even they may be deployed in separate continents with no dependency at all. For example, one application A is running in India and another application is running in USA, and B is interested in getting some updates/messages from A – whenever something unique happen on A. There may be N number of such applications who are interested in such updates from A.

In this scenario, java provides it’s best solution in form of JMS – and solve the exactly same problem discussed above.

The JMS is also useful when we are writing any event based application like chat server where it needs a publish event mechanism to send messages between the server to the clients who are connected with the server. As the JMS is different from RMI so there is no need of the destination object to be available online while sending a message from the client to the server. Server publish the message and forget it, whenever client comes online, it will fetch the message. It’s very powerful solution for very common problems in today’s world.

2. JMS Tutorial – Benefits of JMS

Asynchronous

JMS is asynchronous by default. So to receive a message, the client is not required to send the request. The message will arrive automatically to the client as they become available.

Reliable

JMS provides the facility of assurance that the message will delivered once and only once. You know that duplicate messages create problems. JMS helps you avoiding such problems.

3. JMS Messaging Domains

Before the JMS API existed, most messaging products supported either the point-to-point or the publish/subscribe approach to messaging. The JMS provides a separate domain for each approach and defines the compliance for each domain. Any JMS provider can implement both or one domain, it’s his own choice. The JMS provides the common interfaces which enables us to use the JMS API in such a way that it is not specific to the either domain.

Let’s see both type of messaging domains in more detail to understand how JMS works.

3.1. Point-to-Point Messaging Domain

In the point-to-point messaging domain the application is built on the basis of message queues, senders and receivers. Each and every message is addressed to a particular queue. Queues retain all messages sent to them until the messages are consumed or expired. There are some characteristics of PTP messaging:

  1. There is only one client for each message.
  2. There is no timing dependency for sender and receiver of a message.
  3. The receiver can fetch message whether it is running or not when the sender sends the message.
  4. The receiver sends the acknowledgement after receiving the message.

Point to point JMS Messaging

3.2. Publish/Subscribe Messaging Domain

In publish/subscribe messaging domain, only one message is published which is delivered to all clients through Topic which acts as a bulletin board. Publishers and subscribers are generally anonymous and can dynamically publish or subscribe to the topic. The Topic is responsible to hold and deliver messages. The topic retains messages as long as it takes to distribute to the present clients.

Some of the characteristics are:

  1. There can be multiple subscribers for a message.
  2. The publisher and subscribe have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.

Publish Subscribe JMS Messaging

4. Message Consumption

In JMS, the message consumption can be done in two ways:

4.1. Synchronous

In synchronous message consumption, the subscriber/receiver request the message from the destination by calling the receive() method. In the receive() method will block till the message arrives or time out if the message does not arrive within a given time. Just like normal java method calls with some return value.

4.2. Asynchronous

In asynchronous message consumption, a subscriber can register (or subscribe) as message listener with the consumer. The message listener is same as event listener, whenever the message arrives at the destination the JMS provider will deliver the message by calling the listener’s onMessage() method which will act on the content of the message.

5. JMS participating objects

JMS application has some basic building blocks, which are:

  1. Administered objects – Connection Factories and Destination
  2. Connections
  3. Sessions
  4. Message Producers
  5. Message Consumers
  6. Message Listeners

JMS API Programming Model

5.1. JMS Administered Objects

JMS application provides two types of administered objects:

  • Connection Factories
  • Destinations

These two administered objects are created by JMS system administrator in JMS Provider by using the Application Server the admin console. These both objects are stored in Application server JNDI Directory or JNDI Registry.

5.2. Connection Factories

The client uses an object which is a connection factory used to create a connection to a provider. It creates connection between JMS Provider and JMS Client. When JMS Client such as sender or receiver search out for this object in JNDI Registry, then the JMS Client receives one connection object which is nothing just a physical connection between JMS Provider and JMS Client. Using this connection, client can have communication with the destination object to send or receive messages into Queue or Topic. Let us have an example to understand it to send the message:

5.3. Destination

Client uses an object known as destination which is used to specify the target of messages it produces and the source of message who consumes it. The JMS application uses two types of destination Queue or Topic. The code specifies queue and a topic.

Create queue session

Create topic session

5.4. JMS Connection

The connection encapsulates the virtual connection with a JMS Provider. The connection implements the Connection interface, when it will have a ConnectionFactory object then we can use this to create a connection.

After creating any connection they should be closed before the application completes using:

5.5. JMS Session

The session is a single threaded context which is used for producing and consuming messages. The sessions are used to create the following:

  • Message Producers
  • Message Consumers

The session implements the Session interface and after creating a Connection object we use this to create a Session.

5.6. JMS Message Producer

The message producer is an object which is created by a session and is used for sending messages to the destination. This implements the MessageProducer interface. We use Session to create a MessageProducer for the destination, queue or topic object.

After creating the message producer is used to send the messages by using the send method.

5.7. JMS Message Consumer

The message consumer is an object which is created by a session and is used to receive messages sent at a destination. It will implement the MessageConsumer interface. We use a session to create a MessageConsumer for a destination, queue or topic object.

5.8. JMS Message Listeners

The message listener is an object which acts as asynchronous event handler for messages. The message listener implements the MessageListener interface which contains the one method onMessage() . In this method we define the actions to be performed when message arrives. By using setMessageListener() we define the message listener with a specific MessageConsumer .

Читать еще:  Как исправить ошибку файловой системы

6. JMS Message Components

The JMS Messages are used by the JMS Clients to have communication between systems. The JMS messages have simple format but highly flexible, which allows to create messages which match the formats. The JMS message is divided into three parts. They are:

Message Header

The JMS message header contains the number of predefined fields which contain those values which are used by the clients and providers to identify and send messages. The predefined headers are:

– JMSDestination
– JMSDeliveryMode
– JMSMessageID
– JMSTimestamp
– JMSCorrelationID
– JMSReplyTo
– JMSRedelivered
– JMSType
– JMSExpiration
– JMSPriority

Message Properties

In message properties we can create and set properties for messages. The message properties are custom name value pairs which are set or read by applications. The message properties are useful for supporting filtering messages. The JMS API provides some predefined property that a provider can support. The message property is optional.

Message Body

In message bodies the JMS API defines five message body formats which are also called as message types which allow us to send and receive data in many different forms and also provides compatibility with the existing messaging formats. It basically consists of the actual message sent from JMS sender to receiver. The different message types are:

Text message : Represented by javax.jms.TextMessage. It is used to represent a block of text.
Object message : Represented by javax.jms.ObjectMessage. It is used to represent a java object.
Bytes message : Represented by javax.jms.BytesMessage. It is used to represent the binary data.
Stream message : Represented by javax.jms.StreamMessage. It is used to represent a list of java primitive values.
Map message : Represented by javax.jms.MapMessage. It is used to represent a set of keyword or value pairs.

That’s all for JMS introduction tutorial and it’s related terminologies. In next set of posts. I will give some examples of JMS.

JMS Tutorial – Java Message Service Tutorial

By Lokesh Gupta | Filed Under: JMS

Java Message Service is an API which supports the formal communication called as messaging between computers on a network. It provides a common interface for standard message protocols and message services in support to the Java programs. It provides facility to create, send and read messages. The JMS API reduces the concepts that a programmer must learn to use the messaging services/products and it also provides the features that support the messaging applications.
JMS is a technique which is used in J2EE technology for an application to communicate with the other application in loosely coupled manner. It means that the applications which have to communicate are not connected directly they are connected through a common destination. We will go in detail later in this jms tutorial.

1. JMS Tutorial – Need of JMS

In Java, if a person wants to send a message from one application to another in such a way that both application do not know anything about each other, even they may be deployed in separate continents with no dependency at all. For example, one application A is running in India and another application is running in USA, and B is interested in getting some updates/messages from A – whenever something unique happen on A. There may be N number of such applications who are interested in such updates from A.

In this scenario, java provides it’s best solution in form of JMS – and solve the exactly same problem discussed above.

The JMS is also useful when we are writing any event based application like chat server where it needs a publish event mechanism to send messages between the server to the clients who are connected with the server. As the JMS is different from RMI so there is no need of the destination object to be available online while sending a message from the client to the server. Server publish the message and forget it, whenever client comes online, it will fetch the message. It’s very powerful solution for very common problems in today’s world.

2. JMS Tutorial – Benefits of JMS

Asynchronous

JMS is asynchronous by default. So to receive a message, the client is not required to send the request. The message will arrive automatically to the client as they become available.

Reliable

JMS provides the facility of assurance that the message will delivered once and only once. You know that duplicate messages create problems. JMS helps you avoiding such problems.

3. JMS Messaging Domains

Before the JMS API existed, most messaging products supported either the point-to-point or the publish/subscribe approach to messaging. The JMS provides a separate domain for each approach and defines the compliance for each domain. Any JMS provider can implement both or one domain, it’s his own choice. The JMS provides the common interfaces which enables us to use the JMS API in such a way that it is not specific to the either domain.

Let’s see both type of messaging domains in more detail to understand how JMS works.

3.1. Point-to-Point Messaging Domain

In the point-to-point messaging domain the application is built on the basis of message queues, senders and receivers. Each and every message is addressed to a particular queue. Queues retain all messages sent to them until the messages are consumed or expired. There are some characteristics of PTP messaging:

  1. There is only one client for each message.
  2. There is no timing dependency for sender and receiver of a message.
  3. The receiver can fetch message whether it is running or not when the sender sends the message.
  4. The receiver sends the acknowledgement after receiving the message.

Point to point JMS Messaging

3.2. Publish/Subscribe Messaging Domain

In publish/subscribe messaging domain, only one message is published which is delivered to all clients through Topic which acts as a bulletin board. Publishers and subscribers are generally anonymous and can dynamically publish or subscribe to the topic. The Topic is responsible to hold and deliver messages. The topic retains messages as long as it takes to distribute to the present clients.

Some of the characteristics are:

  1. There can be multiple subscribers for a message.
  2. The publisher and subscribe have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.

Publish Subscribe JMS Messaging

4. Message Consumption

In JMS, the message consumption can be done in two ways:

4.1. Synchronous

In synchronous message consumption, the subscriber/receiver request the message from the destination by calling the receive() method. In the receive() method will block till the message arrives or time out if the message does not arrive within a given time. Just like normal java method calls with some return value.

4.2. Asynchronous

In asynchronous message consumption, a subscriber can register (or subscribe) as message listener with the consumer. The message listener is same as event listener, whenever the message arrives at the destination the JMS provider will deliver the message by calling the listener’s onMessage() method which will act on the content of the message.

5. JMS participating objects

JMS application has some basic building blocks, which are:

  1. Administered objects – Connection Factories and Destination
  2. Connections
  3. Sessions
  4. Message Producers
  5. Message Consumers
  6. Message Listeners

JMS API Programming Model

5.1. JMS Administered Objects

JMS application provides two types of administered objects:

  • Connection Factories
  • Destinations
Читать еще:  Java run application

These two administered objects are created by JMS system administrator in JMS Provider by using the Application Server the admin console. These both objects are stored in Application server JNDI Directory or JNDI Registry.

5.2. Connection Factories

The client uses an object which is a connection factory used to create a connection to a provider. It creates connection between JMS Provider and JMS Client. When JMS Client such as sender or receiver search out for this object in JNDI Registry, then the JMS Client receives one connection object which is nothing just a physical connection between JMS Provider and JMS Client. Using this connection, client can have communication with the destination object to send or receive messages into Queue or Topic. Let us have an example to understand it to send the message:

5.3. Destination

Client uses an object known as destination which is used to specify the target of messages it produces and the source of message who consumes it. The JMS application uses two types of destination Queue or Topic. The code specifies queue and a topic.

Create queue session

Create topic session

5.4. JMS Connection

The connection encapsulates the virtual connection with a JMS Provider. The connection implements the Connection interface, when it will have a ConnectionFactory object then we can use this to create a connection.

After creating any connection they should be closed before the application completes using:

5.5. JMS Session

The session is a single threaded context which is used for producing and consuming messages. The sessions are used to create the following:

  • Message Producers
  • Message Consumers

The session implements the Session interface and after creating a Connection object we use this to create a Session.

5.6. JMS Message Producer

The message producer is an object which is created by a session and is used for sending messages to the destination. This implements the MessageProducer interface. We use Session to create a MessageProducer for the destination, queue or topic object.

After creating the message producer is used to send the messages by using the send method.

5.7. JMS Message Consumer

The message consumer is an object which is created by a session and is used to receive messages sent at a destination. It will implement the MessageConsumer interface. We use a session to create a MessageConsumer for a destination, queue or topic object.

5.8. JMS Message Listeners

The message listener is an object which acts as asynchronous event handler for messages. The message listener implements the MessageListener interface which contains the one method onMessage() . In this method we define the actions to be performed when message arrives. By using setMessageListener() we define the message listener with a specific MessageConsumer .

6. JMS Message Components

The JMS Messages are used by the JMS Clients to have communication between systems. The JMS messages have simple format but highly flexible, which allows to create messages which match the formats. The JMS message is divided into three parts. They are:

Message Header

The JMS message header contains the number of predefined fields which contain those values which are used by the clients and providers to identify and send messages. The predefined headers are:

– JMSDestination
– JMSDeliveryMode
– JMSMessageID
– JMSTimestamp
– JMSCorrelationID
– JMSReplyTo
– JMSRedelivered
– JMSType
– JMSExpiration
– JMSPriority

Message Properties

In message properties we can create and set properties for messages. The message properties are custom name value pairs which are set or read by applications. The message properties are useful for supporting filtering messages. The JMS API provides some predefined property that a provider can support. The message property is optional.

Message Body

In message bodies the JMS API defines five message body formats which are also called as message types which allow us to send and receive data in many different forms and also provides compatibility with the existing messaging formats. It basically consists of the actual message sent from JMS sender to receiver. The different message types are:

Text message : Represented by javax.jms.TextMessage. It is used to represent a block of text.
Object message : Represented by javax.jms.ObjectMessage. It is used to represent a java object.
Bytes message : Represented by javax.jms.BytesMessage. It is used to represent the binary data.
Stream message : Represented by javax.jms.StreamMessage. It is used to represent a list of java primitive values.
Map message : Represented by javax.jms.MapMessage. It is used to represent a set of keyword or value pairs.

That’s all for JMS introduction tutorial and it’s related terminologies. In next set of posts. I will give some examples of JMS.

What is Java Message Service (JMS) for?

I am currently evaluating JMS and I don’t get what I could use it for.

Currently, I believe this would be a Usecase: I want to create a SalesInvoice PDF and print it when an SalesOrder leaves the Warehouse, so during the Delivery transaction I could send a transactional print request which just begins when the SalesOrder transaction completes successfully.

Now I found out most JMS products are standalone server.

  • Why would a need a Standalone Server for Message Processing, vs. e.g. some simple inproc processing with Quartz scheduler?
  • How does it interact with my application?
  • Isn’t it much too slow?
  • What are Usecases you already implemented successfully?

8 Answers 8

JMS is an amazingly useful system, but not for every purpose.

It’s essentially a high-level framework for sending messages between nodes, with options for discovery, robustness, etc.

One useful use case is when you want a client and a server to talk to one another, but without the client actually having the server’s address (E.g., you may have more than one server). The client only needs to know the broker and the queue/topic name, and the server can connect as well.

JMS also adds robustness. For instance, you can configure it so that if the server dies while the client sends messages or the other way around, you can still send messages from the client or poll messages from the server. If you ever tried implementing this directly with sockets — it’s a nightmare.

The scenario you describe sounds like a classic J2EE problem, why are you not using a J2EE framework? JMS is often used inside J2EE for communications, but you got all the other benefits.

What ist Java Message Service (JMS) for

JMS is a messaging standard that allows Java EE applications to create, send, receive, and consume messages in a loosely coupled, reliable, and asynchronous way. I’d suggest to read the Java Message Service API Overview for more details.

Why would a need a Standalone Server for Message Processing, vs. e.g. some simple inproc processing with Quartz scheduler?

Sure, in your case, Quartz is an option. But what if the invoice system is a remote system? What if you don’t want to wait for the answer? What if the remote system is down when you want to communicate with it? What if the network is not always available? This is where JMS comes in. JMS allows to send a message guaranteed to be delivered and to consume it in a transactional way (sending or consuming a message can be part of a global transaction).

How does it interact with my application?

JMS supports two communication modes: point-to-point and publish/subscribe (if this answers the question).

The MOMs I’ve been working with were blazing fast.

What are Usecases you already implemented successfully?

Used in system such as a reservation application, a banking back-office (processing market data), or more simply to send emails.

Ссылка на основную публикацию
Adblock
detector
×
×