Java Messaging Service (JMS) Learning __java

Source: Internet
Author: User
Tags readline sub domain
Recently, there is a project to use JMS, and therefore a little learning.

A messaging service means that two or more clients can communicate by sending and receiving messages (in a peer-to-peer manner). A message is a "piece" of data sent by a client to another client via a message server, either textual or numeric, and the data can include objects if the client is a Java application. Where the client does not need to run concurrently.

Reasons for using the message service:

1. Loosely coupled but high cohesion. Clients that use the messaging service do not need to implement a common interface and do not need to know each other. The messaging service provides a standard interface.

2. No direct communication. The client does not talk directly, but through the intermediary, the messaging service acts as a buffer and provides security control.

3. Ensure message delivery. The provider of the JMS keeps the message persistent until the client accepts it.

4. Asynchronous communication.

5. One-to-many, Many-to-many and Many-to-many communications.

The JMS (Java messaging service) is a standard set of APIs that can be used to access multiple messaging servers. Using JMS, you can use the same APIs to access IBM's MQSeries, JBOSSMQ, and other messaging services.

There are many core concepts in the JMS API that map to the underlying message server. which

1. Controlled objects (administered object). They are objects created by the manager for use by the JMS client. such as connection factories (Connection Factory), which are used to connect to the underlying message server and destination (queues and themes) (note: Not quite understood, may be wrong.) )。 Management manages them through Jndi. JMS provides a buffer between the JMS client and the actual JMS provider. JBoss is the manager of these objects.

2.JMS provider. A messaging server that implements the JMS interface. (such as the JBOSSMQ message server).

3.JMS client. The producers and consumers of the message. Because it is a peer-to-peer communication mechanism, there is no concept of client and server. JMS can be both a message creator and a message recipient.

4. Messages (message). A message that is transmitted between JMS clients.

Traditional messaging services generally support point-to-point communication and publish/subscribe communication in one of two communication modes. The JMS API is supported in two kinds.

Point-to-Point

Point-to-Point communication mode, with a central queue as the target of the publication (the managed object). One or more message producers can send messages to this queue. It is then selected by the consumer of the message.

Pub/sub

The Publish/Subscribe communication model is based on the theme (Topic) concept. The topic is the publication target (the managed object) of the message. It differs from queues in that there can be multiple clients that send and receive messages, and each topic can have multiple publishers and multiple subscribers.

JMS API

The JMS APIs are defined in the JAVAX.JMS package. To use the JMS API, you need to create a connection factory that provides connection objects. The Connection object provides a link to the message server. A link is used to create a session that is used to create a message that is sent through the producer of the message to the target (queue or subject), and then the message is passed to the message consumer.

JMS Parent

PTP Domain

Pub/sub Domain

ConnectionFactory

Queueconnectionfactory

Topicconnectionfactory

Connection

Queueconnection

Topicconnection

Destination

Queue

Topic

Session

Queuesession

Topicsession

MessageProducer

Queuesender

Topicpublisher

Messageconsumer

QueueReceiver

TopicSubscriber

The following is a brief description of these interfaces:

1. Connection Factory (Connection Factory)

Is the object that the client uses to create a link with the JMD provider. It is a managed object and can be found through Jndi. The JMS API defines two types of connection factories. Queueconnectionfactory and Topicconnectionfactory

2. Connection (Connection)

The connection object is the medium that communicates with the JMS provider. The specific implementation of this communication relies on the JMS provider. In addition to the common excuses, there are queueconnection and theme based (topicconnection) private interfaces.

3. Sessions (session)

The producer, consumer, and message used to create the message. They are single-threaded and can participate in the transaction. There are queuesession and topicsession.

4. Messages (Message)

A message is a piece of information sent by a message server between clients. There are five kinds of interfaces, different types of messages. 1. Streammessage--Java Raw Value data flow 2. mapmessage--a set of name/value pairs 3.textmessage--A String Object 4. objectmessage--A serialized Java object 5.bytesmessage--a data stream with no interpreted bytes.

The message consists of the following parts:

Header: The JMS message header contains a number of fields that are generated by the JMS provider or message sender after the message is sent to represent the message, set priority and expiration times, and so on, and determine the route for the message.

Property: is generated by the sender of the message to add additional information other than the header of the deletion message.

Message body: Generated by the sender of the message.

5. Objective (destination)

The target is a controlled object. Represents a queue or a topic in JMS.

6. Message producer (MessageProducer)

Is the object that is used to send messages to the target, created by the session object, with Queuesender, Topicpublisher.

7. Message Consumer (Messageconsumer)

is created by the session object to get messages from the target, with QueueReceiver, TopicSubscriber

A JMS application is a few JMS clients exchanging messages, and developing JMS client applications consists of the following steps:

1) using Jndi to get ConnectionFactory object;

2) using ConnectionFactory to create connection objects;

3 Create one or more JMS sessions with the connection object;

(4) using Jndi to get the target queue or Subject object, namely destination object;

5) to create MessageProducer and Messageconsumer with session and destination;

6 Notify connection to start delivering messages.

The message producer program is as follows

Package org.jms.test;
Import java.io.*;
Mport javax.jms.*;
Import javax.naming.*;
public class Sender {
    public static void Main (string[] args) {
        New Sender (). Send ();
    }
    public void Send () {
        BufferedReader reader = new BufferedReader (new InputStreamReader (system.in));
        try {
            Prompt for JNDI names
            System.out.println ("Enter connectionfactory Name:");
            String factoryname = Reader.readline ();
            System.out.println ("Enter Destination Name:");
            String destinationname = Reader.readline ();
            Look up administered objects
            InitialContext initcontext = new InitialContext ();
            ConnectionFactory factory =
                (connectionfactory) Initcontext.lookup (factoryname);
            Destination Destination = (destination) initcontext.lookup (destinationname);
            Initcontext.close ();
            Create JMS Objects
            Connection Connection = Factory.createconnection ();
            Session session =
                Connection.createsession (False, Session.auto_acknowledge);
            MessageProducer sender = Session.createproducer (queue);
            Send messages
            String messagetext = null;
            while (true) {
                System.out.println ("Enter" to send or ' quit ': ");
                MessageText = Reader.readline ();
                if ("Quit". Equals (MessageText))
                    Break
                TextMessage message = Session.createtextmessage (MessageText);
                Sender.send (message);
            }
            Exit
            System.out.println ("Exiting ...");
            Reader.close ();
            Connection.close ();
            System.out.println ("goodbye!");
        catch (Exception e) {
            E.printstacktrace ();
            System.exit (1);
        }
    }
}

The message consumer program is as follows

Package compute;
Import java.io.*;
Import javax.jms.*;
Import javax.naming.*;
public class Receiver implements MessageListener {
    Private Boolean stop = false;
    public static void Main (string[] args) {
        New Receiver (). receive ();
    
    public void receive () {
        BufferedReader reader = new BufferedReader (new InputStreamReader (system.in));
        try {
            Prompt for JNDI names
            System.out.println ("Enter connectionfactory Name:");
            String factoryname = Reader.readline ();
            System.out.println ("Enter Destination Name:");
            String destinationname = Reader.readline ();
            Reader.close ();
            Look up administered objects
            InitialContext initcontext = new InitialContext ();
            ConnectionFactory factory =
                (connectionfactory) Initcontext.lookup (factoryname);
            Destination Destination = (destination) initcontext.lookup (destinationname);
            Initcontext.close ();
            Create JMS Objects
            Connection Connection = Factory.createconnection ();
            Session session =
                Connection.createsession (False, Session.auto_acknowledge);
            Messageconsumer receiver = Session.createconsumer (queue);
            Receiver.setmessagelistener (this);
            Connection.start ();
            Wait for Stop
            while (!stop) {
                Thread.Sleep (1000);
            }
            Exit
            System.out.println ("Exiting ...");
            Connection.close ();
            System.out.println ("goodbye!");
        catch (Exception e) {
            E.printstacktrace ();
            System.exit (1);
        }
    }
    public void OnMessage (message message) {
        try {
            String Msgtext = ((textmessage) message). GetText ();
            System.out.println (Msgtext);
            if ("Stop". Equals (Msgtext))
                Stop = true;
        catch (JMSException e) {
            E.printstacktrace ();
            Stop = true;
        }
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.