JMS (Java Message Service) Getting Started tutorial (a)

 

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 (sent to the addition and expiration of the message recipient is consumed away). 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); 

创建一个话题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连接

连接对象封装了与JMS提供者之间的虚拟连接,如果我们有一个ConnectionFactory对象,可以使用它来创建一个连接。

Connection connection = connectionFactory.createConnection();

创建完连接后,需要在程序使用结束后关闭它:

connection.close();

JMS 会话(Session)

Session是一个单线程上下文,用于生产和消费消息,可以创建出消息生产者和消息消费者。

Session对象实现了Session接口,在创建完连接后,我们可以使用它创建Session。

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

JMS消息生产者

消息生产者由Session创建,用于往目的地发送消息。生产者实现MessageProducer接口,我们可以为目的地、队列或话题创建生产者;

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

创建完消息生产者后,可以使用send方法发送消息:

producer.send(message);

JMS消息消费者

消息消费者由Session创建,用于接受目的地发送的消息。消费者实现MessageConsumer接口,,我们可以为目的地、队列或话题创建消费者;

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

JMS消息监听器

JMS消息监听器是消息的默认事件处理者,他实现了MessageListener接口,该接口包含一个onMessage方法,在该方法中需要定义消息达到后的具体动作。通过调用setMessageListener方法我们给指定消费者定义了消息监听器

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

JMS消息结构

JMS客户端使用JMS消息与系统通讯,JMS消息虽然格式简单但是非常灵活, JMS消息由三部分组成:

消息头

JMS消息头预定义了若干字段用于客户端与JMS提供者之间识别和发送消息,预编译头如下:

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

消息属性

我们可以给消息设置自定义属性,这些属性主要是提供给应用程序的。对于实现消息过滤功能,消息属性非常有用,JMS API定义了一些标准属性,JMS服务提供者可以选择性的提供部分标准属性。

消息体

在消息体中,JMS API定义了五种类型的消息格式,让我们可以以不同的形式发送和接受消息,并提供了对已有消息格式的兼容。不同的消息类型如下:

Text message : javax.jms.TextMessage,表示一个文本对象。
Object message : javax.jms.ObjectMessage,表示一个JAVA对象。
Bytes message : javax.jms.BytesMessage,表示字节数据。
Stream message :javax.jms.StreamMessage,表示java原始值数据流。
Map message : javax.jms.MapMessage,表示键值对。

Guess you like

Origin www.cnblogs.com/JonaLin/p/11506013.html