SlideShare uma empresa Scribd logo
1 de 9
Java Message Service – Quick learn (hopefully)
                                                                                             Veeramani S
                                                                                       vee.sam@live.com

Messaging ?

Messaging is one of the well known methods to integrate (communicate) two software components
(applications).

Major Benefits?

Asynchronous : Either of the parties (sender or receiver) need not be available at the same time. I.e.
sender can send a message as if the receiver is ready and waiting for the message even though actual
receiver is not active at the time of message sending. (Please note synchronous also possible)

Reliable : Possible to make sure that one message is delivered once and only once. (E.g. A refund
request to the customer should not processed more than one time)

How ?

Every message sent using JMS will be first received by the JMS Queue or Topic and will be available till
the appropriate client consumes the message.

JMS -API?

JMS is JAVA API helps JAVA developers quickly build application with a capable of create, send or
receive message from/to any other application.

Let us have some closer look:

Terminologies :

JMS Provider : Any vendor who is implementing the JMS API specification

JMS Client : Any Java application that creates, sends or receives messages using JMS implementation.

Message : is object from JMS family used to communicate between JMS clients.

Administered objects: Before stating our actual game there should be some infrastructure and
commonly agreed terms for the involved parties. (Destinations and connection factories)




                                                                                                           1
A small story now:




Figure 1 fictional scenario to depict asynchronous messaging and application integration using messaging

Some discussion and clarification from hamazzzon.com story

    1. Should the message server need not to be a standalone always?
          a. No it can be a part of hamazzzon.com application server or Fulfillment vendor
               application server also.
    2. How long a message can wait in the message server?
          a. Administrator of the server can configure, default is 0 which means never expires till the
               message is consumed by a client
    3. Can the same message be available after delivery to the Fulfillment vendor application?
          a. No, Strictly no dupes. Once and only once message will be delivered to the client.
    4. How long a message can wait in the message server?
          a. Queues retain all messages sent to them until the messages are consumed or until the
               messages expire
          b. Administrator of the server can configure the expiry time, default is 0 which means
               never expires till the message is consumed by a client.
    5. What happens if there is an exception?
          a. When an exception occurs while the message consumption
               message it will be marked as unread in the message server
               and will be ready to send for the next message lookup
               request.
          b. Also please note that it is possible to configure after certain
               number of attempts delivery failed message can be moved

                                                                                                           2
to another message (so that hamazzzon can take a look on to it to fix and resend) or
                deleted permanently (in our story it is not wise)
    6. How the message server determines that the message is consumed successfully by the client?
             a. Using the message acknowledge status. We will more about with sample code some
                time later.
    7. Is it possible to include other operation in the same consume call and make it as a single
       transaction (For example vendor wants to update a database)?
             a. YES it is possible transaction support can be extended for this scenario
    8. Is it possible to make the message sender to wait until a message consuming client pick up the
       message?
             a. YES it is possible through ACKNOWLWDGE_MODE setting (then it would turn as
                synchronous* call)

LITTLE more concepts before we start our ROCKING code!

In ancient days most of the MOM(Message Oriented Middleware) or messaging providers support one
of the following category but after the period JMS birth, most(all !) of the messaging providers started
supporting both in single product

Point-to-Point

In this approach single message can be consumed by a single client. Consider our fulfillment story which
is really a point-to-point example, even if our hamazzzon.com has more than one fulfillment vendor only
one of the vendor can/should do the fulfillment.

In JMS call this approached message destination as Queue




                                       Figure 2 Point-to-Point (Queue)

Publisher Subscriber

In this approach single message can be consumed by more than one client. Consider RBI (central bank)
wants to send new rate of interest tariff to all the participant banks the same message has to be
processed by all the banks subscribed.

In JMS call this approached message destination as Topic



                                                                                                           3
Figure 3 Publisher Subscriber (Topic)

Some discussion from these concepts:

   1. If there is more than one message consumption clients in what order message delivered to
      client?
            a. Whoever first calls the receive message method will the chance to consume
            b. However ordering can be defined in the message level so that server can decide which
                message should be delivered first.
   2. Will all the consumer clients in the topic always get the message published in the Topic?
            a. NO. Only the clients online at the time of message publish will the chance to consume
                it.
            b. YES. By marking as durable consumer we can provide the capability to receive messages
                published while the consumer was not active. However this messages are limited from
                the time since durable consumer of a topic created
   3. Is it guarantee that message every will be consumed at least once by its
      client in topic?
            a. No, for example if a topic has all non durable consumers and none
                of them active at the time of message publish then the message
                will not be processed by any client
   4. Now it might sound little late question nevertheless, what actually I can
      send using JMS?
            a. TextMessage, MapMessage, BytesMessage, StreamMessage and
                ObjectMessage




                        If you are not familiar with Administered objects configuration steps, you
                            can get familiar using Weblogic server sample explained in this link.




                                                                                                     4
Where is my code!




                    Figure 4 JMS programming model




                                                     5
Message producer/sender client

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   javax.naming.Context;
import   javax.naming.InitialContext;
import   javax.naming.NamingException;

/**
 * @author sv
 *
 */
public class TestJmsMessageSender {

         public static void main(String[] args) {
               Context jndiContext = null;
               ConnectionFactory connectionFactory = null;
               Connection connection = null;
               Session session = null;
               Destination dest = null;

              /*
               * Setting environment property, this should be ideally come form
               * properties files and should be set through HashMap, But it is
               * OK for our test run
               */

            System.setProperty("java.naming.factory.initial",
                        "weblogic.jndi.WLInitialContextFactory");
            System.setProperty("java.naming.provider.url",
"t3://localhost:7001");


              try {
                      jndiContext = new InitialContext();

                  connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/TestJmsConnectionFactory");
                  dest = (Destination)
jndiContext.lookup("jms/TestJmsQueue");

                      /*
                       * Create connection. Create session from connection; false
means
                       * session is not transacted.
                       */

                      connection = connectionFactory.createConnection();




                                                                                    6
session =
connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);

                        MessageProducer msgProducer = session.createProducer(dest);
                        TextMessage message = session.createTextMessage();

                        message.setText("JMS TextMessage test......");

                  System.out.println("Sending message: " +
message.getText());
                  msgProducer.send(message);
                  System.out.println("Sending message: " +
message.getText());
                  msgProducer.send(message);

                  } catch (NamingException e) {
                        e.printStackTrace();
                  }

                  catch (JMSException e) {
                        System.out.println("Exception occurred: " + e.toString());
                  } finally {
                        if (connection != null) {
                              try {
                                    connection.close();
                              } catch (JMSException e) {
                              }
                        }
                  }
         }
}


Message Consumer/receiver client

import       javax.jms.Connection;
import       javax.jms.ConnectionFactory;
import       javax.jms.Destination;
import       javax.jms.JMSException;
import       javax.jms.MessageConsumer;
import       javax.jms.Queue;
import       javax.jms.QueueConnectionFactory;
import       javax.jms.Session;
import       javax.jms.TextMessage;
import       javax.naming.Context;
import       javax.naming.InitialContext;
import       javax.naming.NamingException;

/**
 * @author sv
 *
 *
 */
public class TestJmsMessageReceiver {



                                                                                      7
public static void main(String[] args) {
              Context jndiContext = null;
              ConnectionFactory connectionFactory = null;
              Connection connection = null;
              Session session = null;
              Destination dest = null;

            /*
             * Setting environment property
             */
            System.setProperty("java.naming.factory.initial",
                        "weblogic.jndi.WLInitialContextFactory");
            System.setProperty("java.naming.provider.url",
"t3://localhost:7001");


              try {
                      jndiContext = new InitialContext();

                  connectionFactory = (QueueConnectionFactory)
jndiContext.lookup("jms/TestJmsConnectionFactory");
                  dest = (Queue) jndiContext.lookup("jms/TestJmsQueue");

                      /*
                       * Create connection. Create session from connection; false
means
                       * session is not transacted. Create sender and text
message. Send
                       * messages, varying text slightly. Finally, close
connection.
                       */

                      connection = connectionFactory.createConnection();

                  session =
connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
                  connection.start();

                      MessageConsumer consumer = session.createConsumer(dest);


                  TextMessage message =    (TextMessage)
consumer.receive(1000);
                  System.out.println(message.getText());

                      message =    (TextMessage) consumer.receive(1000);
                      System.out.println(message.getText());
                      message.acknowledge();

                      //queueSession.commit();

              } catch (NamingException e) {
                    e.printStackTrace();
                                      System.exit(1);
              }

              catch (JMSException e) {

                                                                                    8
System.out.println("Exception occurred: " + e.toString());
                }
                catch(Exception e){
                      e.printStackTrace();
                }
                finally {
                      if (connection != null) {
                            try {
                                  connection.close();
                            } catch (JMSException e) {
                            }
                      }
                }
        }
}



/! Trap zone :

    1. Any acknowledge mode will be ignored if the transaction is enable in a session

             For example in the following code transaction flag is set as “true” hence whatever
             acknowledgement mode provided here will be ignored and set as “AUTO_ACKNOWLEDGE”,
             if the transaction succeeds then message will get automatically acknowledge ( using which
             means server will determine whether to remove the message or to redeliver).

             QueueSession queueSession createQueueSession(true,Session.
             CLIENT_ACKNOWLEDGE);

    2. UserTransaction handling is allowed only for the MDBs configured as Bean-managed
       transactions
           a. For example messageDrivenContext.getUserTransaction().begin() will throw an
               exception if it called from a MDB which is configured as Container transitioned
    3. MessageDrivenContext’s setRollbackOnly() would cause the server to re-deliver the message
       again. However this is legal only if the provider(connection factory) is XA transaction enabled

    4. MDB acknowledge mode can either “Auto-Acknowledge” or “DUPS_OK_ACKNOWLEDGE” any
       other mode is not allowed
    5. Throwing an exception in the onMessage() method of MDB make the server to re-deliver the
       message again
    6. Security is depends on the provider and it’s a architectural decision.


Exercise :

Set a Topic in your application server and try a similar program
Try to set up MDB and consume message send from a producer.
In case of any clarification please contact me though my email, I will try to resolve.


                                                                                                         9

Mais conteúdo relacionado

Mais procurados (11)

Solace Integration with Mulesoft
Solace Integration with MulesoftSolace Integration with Mulesoft
Solace Integration with Mulesoft
 
Jms
JmsJms
Jms
 
Jms
JmsJms
Jms
 
Understanding JMS Integration Patterns
Understanding JMS Integration Patterns Understanding JMS Integration Patterns
Understanding JMS Integration Patterns
 
Java Messaging Services
Java Messaging ServicesJava Messaging Services
Java Messaging Services
 
Jms intro
Jms introJms intro
Jms intro
 
Jms
JmsJms
Jms
 
SMS API InforUMobile
SMS API InforUMobileSMS API InforUMobile
SMS API InforUMobile
 
SMS API InforUMobile
SMS API InforUMobileSMS API InforUMobile
SMS API InforUMobile
 
test
testtest
test
 
test
testtest
test
 

Destaque

Clasificación de las redes por cobertura
Clasificación de las redes por coberturaClasificación de las redes por cobertura
Clasificación de las redes por coberturaLuisa Bedoya Valencia
 
60 lecie Koła Łowieckiego Knieja
60 lecie Koła Łowieckiego Knieja60 lecie Koła Łowieckiego Knieja
60 lecie Koła Łowieckiego Kniejakacpersky21
 
Y si les parecio
Y si les parecioY si les parecio
Y si les parecioPepe030597
 
Ap3d seo young deok
Ap3d seo young deokAp3d seo young deok
Ap3d seo young deokFlorence
 
Apah abet 8 presentation
Apah abet 8 presentationApah abet 8 presentation
Apah abet 8 presentationFlorence
 
Administered object config
Administered object configAdministered object config
Administered object configVeeramani S
 

Destaque (7)

Clasificación de las redes por cobertura
Clasificación de las redes por coberturaClasificación de las redes por cobertura
Clasificación de las redes por cobertura
 
Internet
InternetInternet
Internet
 
60 lecie Koła Łowieckiego Knieja
60 lecie Koła Łowieckiego Knieja60 lecie Koła Łowieckiego Knieja
60 lecie Koła Łowieckiego Knieja
 
Y si les parecio
Y si les parecioY si les parecio
Y si les parecio
 
Ap3d seo young deok
Ap3d seo young deokAp3d seo young deok
Ap3d seo young deok
 
Apah abet 8 presentation
Apah abet 8 presentationApah abet 8 presentation
Apah abet 8 presentation
 
Administered object config
Administered object configAdministered object config
Administered object config
 

Semelhante a Java message service

Semelhante a Java message service (20)

test validation
test validationtest validation
test validation
 
Test DB user
Test DB userTest DB user
Test DB user
 
Apache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache CamelApache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache Camel
 
Jms
JmsJms
Jms
 
#7 (Java Message Service)
#7 (Java Message Service)#7 (Java Message Service)
#7 (Java Message Service)
 
Jms topics
Jms topicsJms topics
Jms topics
 
Indianapolis mule soft_meetup_12_june_2021
Indianapolis mule soft_meetup_12_june_2021Indianapolis mule soft_meetup_12_june_2021
Indianapolis mule soft_meetup_12_june_2021
 
Mule jms-topics
Mule jms-topicsMule jms-topics
Mule jms-topics
 
Jms session (1)
Jms session (1)Jms session (1)
Jms session (1)
 
JMS - Java Messaging Service
JMS - Java Messaging ServiceJMS - Java Messaging Service
JMS - Java Messaging Service
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
M messaging 1
M messaging 1M messaging 1
M messaging 1
 
Java Message Service
Java Message ServiceJava Message Service
Java Message Service
 
Jms topics
Jms   topicsJms   topics
Jms topics
 

Último

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Último (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

Java message service

  • 1. Java Message Service – Quick learn (hopefully) Veeramani S vee.sam@live.com Messaging ? Messaging is one of the well known methods to integrate (communicate) two software components (applications). Major Benefits? Asynchronous : Either of the parties (sender or receiver) need not be available at the same time. I.e. sender can send a message as if the receiver is ready and waiting for the message even though actual receiver is not active at the time of message sending. (Please note synchronous also possible) Reliable : Possible to make sure that one message is delivered once and only once. (E.g. A refund request to the customer should not processed more than one time) How ? Every message sent using JMS will be first received by the JMS Queue or Topic and will be available till the appropriate client consumes the message. JMS -API? JMS is JAVA API helps JAVA developers quickly build application with a capable of create, send or receive message from/to any other application. Let us have some closer look: Terminologies : JMS Provider : Any vendor who is implementing the JMS API specification JMS Client : Any Java application that creates, sends or receives messages using JMS implementation. Message : is object from JMS family used to communicate between JMS clients. Administered objects: Before stating our actual game there should be some infrastructure and commonly agreed terms for the involved parties. (Destinations and connection factories) 1
  • 2. A small story now: Figure 1 fictional scenario to depict asynchronous messaging and application integration using messaging Some discussion and clarification from hamazzzon.com story 1. Should the message server need not to be a standalone always? a. No it can be a part of hamazzzon.com application server or Fulfillment vendor application server also. 2. How long a message can wait in the message server? a. Administrator of the server can configure, default is 0 which means never expires till the message is consumed by a client 3. Can the same message be available after delivery to the Fulfillment vendor application? a. No, Strictly no dupes. Once and only once message will be delivered to the client. 4. How long a message can wait in the message server? a. Queues retain all messages sent to them until the messages are consumed or until the messages expire b. Administrator of the server can configure the expiry time, default is 0 which means never expires till the message is consumed by a client. 5. What happens if there is an exception? a. When an exception occurs while the message consumption message it will be marked as unread in the message server and will be ready to send for the next message lookup request. b. Also please note that it is possible to configure after certain number of attempts delivery failed message can be moved 2
  • 3. to another message (so that hamazzzon can take a look on to it to fix and resend) or deleted permanently (in our story it is not wise) 6. How the message server determines that the message is consumed successfully by the client? a. Using the message acknowledge status. We will more about with sample code some time later. 7. Is it possible to include other operation in the same consume call and make it as a single transaction (For example vendor wants to update a database)? a. YES it is possible transaction support can be extended for this scenario 8. Is it possible to make the message sender to wait until a message consuming client pick up the message? a. YES it is possible through ACKNOWLWDGE_MODE setting (then it would turn as synchronous* call) LITTLE more concepts before we start our ROCKING code! In ancient days most of the MOM(Message Oriented Middleware) or messaging providers support one of the following category but after the period JMS birth, most(all !) of the messaging providers started supporting both in single product Point-to-Point In this approach single message can be consumed by a single client. Consider our fulfillment story which is really a point-to-point example, even if our hamazzzon.com has more than one fulfillment vendor only one of the vendor can/should do the fulfillment. In JMS call this approached message destination as Queue Figure 2 Point-to-Point (Queue) Publisher Subscriber In this approach single message can be consumed by more than one client. Consider RBI (central bank) wants to send new rate of interest tariff to all the participant banks the same message has to be processed by all the banks subscribed. In JMS call this approached message destination as Topic 3
  • 4. Figure 3 Publisher Subscriber (Topic) Some discussion from these concepts: 1. If there is more than one message consumption clients in what order message delivered to client? a. Whoever first calls the receive message method will the chance to consume b. However ordering can be defined in the message level so that server can decide which message should be delivered first. 2. Will all the consumer clients in the topic always get the message published in the Topic? a. NO. Only the clients online at the time of message publish will the chance to consume it. b. YES. By marking as durable consumer we can provide the capability to receive messages published while the consumer was not active. However this messages are limited from the time since durable consumer of a topic created 3. Is it guarantee that message every will be consumed at least once by its client in topic? a. No, for example if a topic has all non durable consumers and none of them active at the time of message publish then the message will not be processed by any client 4. Now it might sound little late question nevertheless, what actually I can send using JMS? a. TextMessage, MapMessage, BytesMessage, StreamMessage and ObjectMessage If you are not familiar with Administered objects configuration steps, you can get familiar using Weblogic server sample explained in this link. 4
  • 5. Where is my code! Figure 4 JMS programming model 5
  • 6. Message producer/sender client 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 javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * @author sv * */ public class TestJmsMessageSender { public static void main(String[] args) { Context jndiContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination dest = null; /* * Setting environment property, this should be ideally come form * properties files and should be set through HashMap, But it is * OK for our test run */ System.setProperty("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory"); System.setProperty("java.naming.provider.url", "t3://localhost:7001"); try { jndiContext = new InitialContext(); connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/TestJmsConnectionFactory"); dest = (Destination) jndiContext.lookup("jms/TestJmsQueue"); /* * Create connection. Create session from connection; false means * session is not transacted. */ connection = connectionFactory.createConnection(); 6
  • 7. session = connection.createSession(false,Session.CLIENT_ACKNOWLEDGE); MessageProducer msgProducer = session.createProducer(dest); TextMessage message = session.createTextMessage(); message.setText("JMS TextMessage test......"); System.out.println("Sending message: " + message.getText()); msgProducer.send(message); System.out.println("Sending message: " + message.getText()); msgProducer.send(message); } catch (NamingException e) { e.printStackTrace(); } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } } } Message Consumer/receiver client import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.Queue; import javax.jms.QueueConnectionFactory; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * @author sv * * */ public class TestJmsMessageReceiver { 7
  • 8. public static void main(String[] args) { Context jndiContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination dest = null; /* * Setting environment property */ System.setProperty("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory"); System.setProperty("java.naming.provider.url", "t3://localhost:7001"); try { jndiContext = new InitialContext(); connectionFactory = (QueueConnectionFactory) jndiContext.lookup("jms/TestJmsConnectionFactory"); dest = (Queue) jndiContext.lookup("jms/TestJmsQueue"); /* * Create connection. Create session from connection; false means * session is not transacted. Create sender and text message. Send * messages, varying text slightly. Finally, close connection. */ connection = connectionFactory.createConnection(); session = connection.createSession(false,Session.CLIENT_ACKNOWLEDGE); connection.start(); MessageConsumer consumer = session.createConsumer(dest); TextMessage message = (TextMessage) consumer.receive(1000); System.out.println(message.getText()); message = (TextMessage) consumer.receive(1000); System.out.println(message.getText()); message.acknowledge(); //queueSession.commit(); } catch (NamingException e) { e.printStackTrace(); System.exit(1); } catch (JMSException e) { 8
  • 9. System.out.println("Exception occurred: " + e.toString()); } catch(Exception e){ e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } } } /! Trap zone : 1. Any acknowledge mode will be ignored if the transaction is enable in a session For example in the following code transaction flag is set as “true” hence whatever acknowledgement mode provided here will be ignored and set as “AUTO_ACKNOWLEDGE”, if the transaction succeeds then message will get automatically acknowledge ( using which means server will determine whether to remove the message or to redeliver). QueueSession queueSession createQueueSession(true,Session. CLIENT_ACKNOWLEDGE); 2. UserTransaction handling is allowed only for the MDBs configured as Bean-managed transactions a. For example messageDrivenContext.getUserTransaction().begin() will throw an exception if it called from a MDB which is configured as Container transitioned 3. MessageDrivenContext’s setRollbackOnly() would cause the server to re-deliver the message again. However this is legal only if the provider(connection factory) is XA transaction enabled 4. MDB acknowledge mode can either “Auto-Acknowledge” or “DUPS_OK_ACKNOWLEDGE” any other mode is not allowed 5. Throwing an exception in the onMessage() method of MDB make the server to re-deliver the message again 6. Security is depends on the provider and it’s a architectural decision. Exercise : Set a Topic in your application server and try a similar program Try to set up MDB and consume message send from a producer. In case of any clarification please contact me though my email, I will try to resolve. 9