Java Message Service (JMS) Learning Summary

Source: Internet
Author: User
Tags sub domain

There is a project that uses JMS, so I learned a little bit.
Messageservice means that two or more clients can communicate by sending and receiving messages (in a peering manner. A message is a piece of "data" sent from one client to another through the message server. It can be text or numeric. If the client is a Java application, the data can also contain objects. The client does not need to run at the same time.
Reasons for using MnS:
1. Loose coupling but high cohesion. Clients that use MnS do not need to implement common interfaces or understand each other. Message Service provides standard interfaces.
2. No direct communication. Instead of directly speaking to the client, the Message Service acts as a buffer through the intermediate media and provides security control.
3. Ensure message transmission. The JMS provider keeps the message persistent until the client accepts it.
4. asynchronous communication.
5. One-to-multiple, multi-to-many, and multi-to-one communication.
Java Message Service (JMS) is a set of standard APIs that can be used to access multiple message servers. With JMS, you can use the same API to access MnS such as IBM MQSeries and JBossMQ.
Many core concepts of JMS APIs are mapped to the underlying Messaging Server. Where:
1. controlled Object (Administered Object ). They are the objects created by the Administrator for the JMS client. For example, Connection Factory is used to connect to the underlying message server and target (queue and topic .). Manage 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. Message Server that implements the JMS interface. (For example, JBossMQ Message Server ).
3. JMS client. The producer and consumer of the message. Because it is a peering communication mechanism, there is no concept of a client and a server. JMS can be both the message creator and the message receiver.
4. Message ). Messages sent between JMS clients.
Traditional Message Service generally supports two communication modes: point-to-point communication and publish/subscribe communication. Both JMS APIs are supported.
 
Point-To-Point
In point-to-point communication mode, there is a central queue as the target (controlled object) for publishing ). One or more message producers can send messages to this queue. Then it is selected by the consumer of the message.
 
Pub/Sub
The Publish/subscribe communication mode is based on the Topic concept. The topic is the publishing target (controlled object) of a message ). Different from the queue, MQ can have multiple clients that send and receive messages. Each topic can have multiple publishers and subscribers.
 
JMS API
The jms api is defined in the javax. jms package. To use the jms api, you must create a connection factory that provides the connection object. The connection object provides a link to the Message Server. A link is used to create a session. A session is used to create a message. A message is sent to the target (queue or topic) through the message producer, and then the message is sent 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)
Is the object used by the client to create a connection with the JMD provider. It is a controlled object and can be searched through JNDI. The jms api defines two types of connection factories. QueueConnectionFactory and TopicConnectionFactory
2. Connection)
The connection object is a medium for communication with the JMS provider. The specific implementation of this communication depends on the JMS provider. In addition to common excuses, there are also queue-based (QueueConnection) and topic-based (TopicConnection)-specific interfaces.
3. Session)
Creates the producer, consumer, and message of a message. They are all single-threaded and can participate in transactions. QueueSession and TopicSession.
4. Message)
A message is a piece of information sent by the Message Server between clients. There are five interfaces for different types of messages. 1. streamMessage -- data stream of the original Java value 2. mapMessage -- a group of name/value pairs 3. textMessage -- A String object 4. objectMessage -- A serialized Java object 5. bytesMessage-An uninterpreted byte data stream.
A Message consists of the following parts:
Header: a jms header contains many fields. After a message is sent, it is generated by the JMS provider or message sender to indicate the message, set priority and expiration time, determine the route for the message.
Property: it is generated by the message sender and used to add and delete additional information other than the message header.
Body: generated by the message sender.
5. Destination)
The target is a controlled object. Indicates a queue or topic in JMS.
6. MessageProducer)
Is the object used to send messages to the target. It is created by the session object, including QueueSender and TopicPublisher.
7. MessageConsumer)
Is created by a session object to obtain messages from the target, including QueueReceiver and TopicSubscriber.
 
A jms application exchange messages between several JMS clients. The development of a JMS client application consists of the following steps:
1) Use JNDI to obtain the ConnectionFactory object;
2) use ConnectionFactory to create a Connection object;
3) create one or more JMS sessions with the Connection object;
4) use JNDI to obtain the target queue or topic object, that is, the Destination object;
5) Use Session and Destination to create MessageProducer and MessageConsumer;
6) notify the Connection to start transmitting the message.
The message producer program is as follows:
[Java]
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 message 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:
[Java]
Package compute;
Import java. io .*;
Import javax. jms .*;
Import javax. naming .*;
Public class extends er implements MessageListener {
Private boolean stop = false;
Public static void main (String [] args ){
New Receiver Er (). 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 consumer ER = session. createConsumer (queue );
Aggreger. 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;
}
}
}


Author: luqin1988

Related Article

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.