Learning JMS (java)

What is the Java Message Service

It refers to the Java Message Service for asynchronous communication between two application API, which provides a common interface for the standard message protocols and message services, including create, send, read messages, etc., to support the JAVA application development . In J2EE, when two JMS application uses to communicate between them are not directly connected, but are connected together through a common messaging service, the decoupling effect can be achieved, we will in the next tutorial in detail.

Why do we need JMS

In JAVA, if between the two applications do not understand on their own, even these two programs may be deployed on different continents, so how to send messages between them? For example, an application deployed in India A, another application deployed in the United States, then something is triggered whenever A, B want to get some updated information from A. Of course, there may be more than one update information of interest to the A, B, B may be similar to the N applications want to obtain updated information from the A.

  In this case, JAVA provides the best solution -JMS, the perfect solution to the problems discussed above.

  The same applies to JMS-based application events, such as chat service, which requires a release mechanism to send an event message to all clients connected to the server. JMS and RMI is different when sending a message, the recipient does not need online. The server sends a message, then the matter; wait until the client on the line, to ensure receipt of the message sent by the server. This is a very powerful solution that can handle many common problems in today's world.

JMS advantage

asynchronous

  JMS is inherently asynchronous, when the client gets the message and does not need to take the initiative to send a request, a message is automatically sent to the client available.

reliable

  JMS to ensure that messages are only delivered once. We have encountered repeated problems create a message, and JMS help you avoid this problem.

JMS messaging model

Before JMS API appears, most of the products using the "point" and "publish / subscribe" in either way to communicate a message. JMS defines two messaging specification models, they are independent of each other. Any JMS provider can implement one or two models of them, it is their own choice. JMS specification provides a common interface to ensure that the program prepared by us based JMS API is applicable to any model.

  Let us look at this in more detail two message delivery models:

Point to point messaging model

  In the point to point messaging model, the application message queue by the sender, the receiver components. Each message sent to a special message queue that stores all its messages (except expired and the recipient of the message is consumed out) sent. Point to point messaging model has some characteristics as follows:

  • Each message is only one recipient;
  • Message sender and receiver do not have time-dependent;
  • When the message sender to send a message, regardless of the recipient in the program is not running, you can get the message;
  • When the recipient receives the message, it will send acknowledgment of receipt (acknowledgement).

Publish / subscribe messaging model

  In the publish / subscribe messaging model, the publisher released a message, and the message to all clients by topic. In this model, publishers and subscribers who do not know about each other, are anonymous and can dynamically publish and subscribe topic. The main topic for saving and deliver the message, and the message remains stored until the message is delivered to the client.

Publish / subscribe messaging model characteristics are as follows:

  • A message can be passed to a plurality of subscribers
  • Publishers and Subscribers have time-dependent only when the client creates a subscription to receive messages, and subscribers need to remain active to receive messages.
  • In order to alleviate such strict time correlation, JMS allows subscribers to create a persistent subscription. Thus, even if the subscriber is not activated (run), it can also receive the message publisher.

Receive messages

In JMS, the received message may be used in two ways:

Synchronize

  Receive messages using the synchronization mode, then the message subscriber call receive () method. In the receive (), the message does not reach the specified time or before, the method will be blocked until a message is available.

asynchronous

  Asynchronously receive messages, then the message subscribers need to register a message listener, similar to an event listener, as long as the message arrives, JMS service provider will deliver the message by calling the listener's onMessage ().

JMS Programming Interface

JMS application consists of the following basic modules:

  1. Management Objects (Administered objects) - connection factory (Connection Factories) and the destination (the Destination)
  2. Connection object (the Connections)
  3. Sessions (Sessions)
  4. Producers message (Message Producers)
  5. Message consumer (Message Consumers)
  6. Message listener (Message Listeners)

JMS administered objects

Management Objects (Administered objects) are preconfigured JMS objects created by the system administrator to use a JMS client, there are two objects to be managed:

  • Connection factory (the ConnectionFactory)
  • Destination (Destination)

The two managed objects by using the Application Server administrative console created by the system administrator JMS, JNDI name space or JNDI registry is stored in the application server.

Connection factory (the ConnectionFactory)

The client uses a JMS connection factory object to connect to the service provider, it creates a connection between the JMS service provider and the client. JMS client (such as sender or recipient) searches for and acquires the connection JNDI name space. Using this connection, the client can, subject to the queue, or send / receive messages with a destination communication. Let's use an example to understand how to send a message:

QueueConnectionFactory queueConnFactory = (QueueConnectionFactory) initialCtx.lookup ("primaryQCF");
Queue purchaseQueue = (Queue) initialCtx.lookup ("Purchase_Queue");
Queue returnQueue = (Queue) initialCtx.lookup ("Return_Queue");

Destination (Destination)

Specified destination, and the destination client receiving the message was sent the message source. JMS using two destinations, queues and topics. Following code specifies a queue and topic.

Creating a queue Session

QueueSession ses = con.createQueueSession (false, Session.AUTO_ACKNOWLEDGE);  //get the Queue object  
Queue t = (Queue) ctx.lookup ("myQueue");  //create QueueReceiver  
QueueReceiver receiver = ses.createReceiver(t); 

Create a topic Session

TopicSession ses = con.createTopicSession (false, Session.AUTO_ACKNOWLEDGE); // get the Topic object  
Topic t = (Topic) ctx.lookup ("myTopic");  //create TopicSubscriber  
TopicSubscriber receiver = ses.createSubscriber(t);  

JMS connection

Connection object encapsulates a virtual connection between the provider and JMS are, if we have a ConnectionFactory object, you can use it to create a connection.

Connection connection = connectionFactory.createConnection();

After creating the connection, you need to close it after the end of the program to use:

connection.close();

JMS session (Session)

Session is a single-threaded context for producing and consuming messages, you can create message producers and message consumers.

Session Session object implements the interface after creating the connections, we can use it to create Session.

Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

JMS message producer

News producers created by the Session, used to send messages to the destination. Producers realize MessageProducer interface, we can create a producer as a destination, queue or topic;

MessageProducer producer = session.createProducer(dest);
MessageProducer producer = session.createProducer(queue);
MessageProducer producer = session.createProducer(topic);

After you create message producers can send messages using the send method:

producer.send(message);

JMS message consumer

News consumers created by the Session, to accept the message sent by the destination. Consumers realize MessageConsumer interfaces ,, we can create a consumer destination, queue or topic;

MessageConsumer consumer = session.createConsumer(dest);
MessageConsumer consumer = session.createConsumer(queue);
MessageConsumer consumer = session.createConsumer(topic);

JMS message listener

JMS message listener is the default event handler message, he realized MessageListener interface, which contains a onMessage method, you need to define specific action after the news reached in the process. SetMessageListener by calling the method we defined the consumer to specify message listeners

Listener myListener = new Listener();
consumer.setMessageListener(myListener);

JMS client uses JMS messaging systems and communications, JMS messages though simple but very flexible format, JMS message consists of three parts:

Header

JMS message header a number of predefined fields for identifying and sending messages between the client and the JMS provider, precompiled header as follows:

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

Message Properties

We can give the message set custom properties, which are mainly provided to the application. For achieving message filtering, message property is useful, JMS the API standard defines several properties, JMS service provider may selectively provide some standard attributes.

Message Body

In the message body, JMS API defines five types of message formats, so that we can send and receive messages, and provides compatibility with existing message formats in different forms. Different message types are as follows:

The Message Text  : javax.jms.TextMessage, represents a text object.
The Message Object  : javax.jms.ObjectMessage, represents a JAVA object.
Message bytes  : javax.jms.BytesMessage, represents byte data.
Message Stream  : javax.jms.StreamMessage, the value represents the original data stream java.
The Message the Map  : javax.jms.MapMessage, expressed pairs.

 

Use Case column: based on Tomcat + JNDI + ActiveMQ JMS achieve peer to peer messaging
JMS publish / subscribe messaging example

https://www.cnblogs.com/chenpi/p/5566983.html

 

 

Guess you like

Origin blog.csdn.net/chehec2010/article/details/93471826