JMS details 2

Source: Internet
Author: User
  • Java Message Service (JMS) Details
    This article introduces the Message Service JMS in Java. Java Message Service provides the point-to-point mode and the publish-subscribe mode. These two services are described in detail in this article.

     

    Java Message Service (JMS Java Message Services) provides point-to-point queue and publish-subscribe modes ).

    Queue only allows one message to be sent to one customer (one-to-one ):

    There is no time dependency between the receiver and the sender of Java Message Service JMS. The receiver can extract information regardless of whether the receiver is running when the sender sends the message. The recipient provides a receipt for successfully processed messages.

    Topics can have multiple clients (one to multiple, multiple to multiple ):

    The client program that subscribes to a topic can only receive messages published after it subscribes. To receive messages, the subscriber must remain active. Therefore, there is a time dependency between the publisher and the subscriber.

    The point-to-point message mode is implemented through a queue. The producer of a message writes a message to the queue, and the subscriber of the message extracts the message from the queue. The publish-subscribe message mode is implemented through a layered structure composed of a topic node. The message producer publishes messages to this hierarchy, and the subscriber of the message subscribes to the message.

    The message-driven bean has only one bean class. In some respects, the JMS message-driven bean is similar to the stateless Session Bean: the message-driven bean does not retain data or conversation status for specific customers.

 
 
  1. @MessageDriven(activationConfig={  
  2.    @ActivationConfigProperty(propertyName="destinationType",propertyValue="javax.jms.Queue"),  
  3.    @ActivationConfigProperty(propertyName="destination",propertyValue="queue/jms")  
  4. }) 

@ Messagedriven the comment indicates that this is a message-driven bean and uses @ activationconfigproperty to annotate various attributes of the message. The destinationtype attribute specifies the type of the message. There are two types of messages: topics and queues, the following describes the two types of messages:

Topics can have multiple clients. Topic publishing allows one-to-multiple or multiple-to-multiple communication channels. The publisher of a message is called publisher, and the receiver of Java Message Service is called subscriber. Destinationtype attribute value: javax. JMS. Topic

Queue only allows one message to be sent to one customer. A sender puts a message into the message queue. The receiver extracts and obtains the message from the queue, and the message disappears in the queue. After the first receiver extracts and obtains the message, others cannot obtain it. Destinationtype attribute value: javax. JMS. the queue destination attribute is used to specify the message path. When a message-driven bean is published, if the path does not exist, the container automatically creates the path. when the container is closed, the path is automatically deleted.

When a message arrives in the queue/JMS queue, the onmessage method is triggered and the message is passed in as a parameter.

 
 
  1. package com.julycn.jms;  
  2.  
  3. import javax.ejb.ActivationConfigProperty;  
  4. import javax.ejb.MessageDriven;  
  5. import javax.jms.JMSException;  
  6. import javax.jms.Message;  
  7. import javax.jms.MessageListener;  
  8. import javax.jms.TextMessage;  
  9.  
  10. @MessageDriven(activationConfig = {  
  11.         @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),  
  12.         @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/jms") })  
  13. public class MessageQueue implements MessageListener {  
  14.  
  15.     public MessageQueue() {  
  16.  
  17.     }  
  18.  
  19.     public void onMessage(Message message) {  
  20.         TextMessage tmsg = (TextMessage) message;  
  21.         try {  
  22.             System.out.println(tmsg.getText());  
  23.         } catch (JMSException e) {  
  24.             e.printStackTrace();  
  25.         }  
  26.     }  
  27.  
 
 
  1. PackageCom. julycn. client;
  2.  
  3. ImportJavax. JMS. jmsexception;
  4. ImportJavax. JMS. Queue;
  5. ImportJavax. JMS. queueconnection;
  6. ImportJavax. JMS. queueconnectionfactory;
  7. ImportJavax. JMS. queuesender;
  8. ImportJavax. JMS. queuesession;
  9. ImportJavax. JMS. textmessage;
  10. ImportJavax. Naming. initialcontext;
  11. ImportJavax. Naming. namingexception;
  12.  
  13. Public ClassMessagequeueclient {
  14.  
  15. Public Static VoidMain (string [] ARGs ){
  16. Queueconnection conn;
  17. Queuesession;
  18. Queue queue;
  19. Queuesender sender;
  20. Textmessage MSG;
  21.  
  22. Try{
  23. Initialcontext CTX =NewInitialcontext ();
  24. Queueconnectionfactory qcf = (queueconnectionfactory) CTX
  25. . Lookup ("connectionfactory ");
  26. Conn = qcf. createqueueconnection ();
  27. Session = conn. createqueuesession (False,
  28. Queuesession. auto_acknowledge );
  29. Queue = (Queue) CTX. Lookup ("queue/JMS ");
  30. MSG = session. createtextmessage ("hello, I haven't seen you for a long time! ");
  31. Sender = session. createsender (Queue );
  32. Sender. Send (MSG );
  33. Sender. Close ();
  34. }Catch(Namingexception e ){
  35. E. printstacktrace ();
  36. }Catch(Jmsexception e ){
  37. E. printstacktrace ();
  38. }
  39.  
  40. }
  41.  
  42. }

(1) Get a JNDI initialization context (context );

Sample Code:

Properties props = new properties ();
Props. setproperty ("Java. Naming. Factory. Initial", "org. jnp. Interfaces. namingcontextfactory ");
Props. setproperty ("Java. Naming. provider. url", "localhost: 1099 ");
Props. setproperty ("Java. Naming. Factory. url. pkgs", "org. JBoss. Naming ");
Initialcontext CTX = new initialcontext (props );

Note: It can be written in the Code or in the JNDI. properties file.

(2) Search for a connection factory topicconnectfactory/queueconnectionfactory Based on the context (there are two connection factories, the corresponding type is used based on the topic/Queue );

Sample Code:

Queueconnectionfactory qcf = (queueconnectionfactory) CTX. Lookup ("connectionfactory ");

(3) Get a connection from the connection Factory (connect has two [topicconnection/queueconnection]);

Example code: conn = qcf. createqueueconnection ();

(4) Establish a session through a connection );

Example code: Session = conn. createqueuesession (false, queuesession. auto_acknowledge );

This Code indicates that a session that does not need transactions and can automatically receive Java Message Service receipts is established. In non-transaction sessions, there are three methods for passing JMS messages:
Session. auto_acknowledge: when the client calls the receive method and messagelistenser successfully processes the message, the session automatically receives the message receipt.

Session. client_acknowledge: the client receives a message by calling the acknowledge method of the message. The message is received at the Session Layer. When a consumed message is received, all messages that have been consumed by the session are automatically received. For example, if the consumer consumes 10 messages and receives 15 messages, the receipt of the first 10 messages will be received in the 15 messages.

Session. dups_acknowledge: indicates that the session receives messages slowly.

(5) Search for the destination (topic/Queue );

Example code: queue = (Queue) CTX. Lookup ("queue/JMS ");

(6) create a message producer (topicpublisher/queuesender) and a consumer (topicsubscriber/queuereceiver) based on the session and destination ).
Sample Code:

MSG = session. createtextmessage ("hello, I haven't seen you for a long time! ");
Sender = session. createsender (Queue );
Sender. Send (MSG );

NOTE: If javax. Naming. namenotfoundexception: JMS not bound occurs during runtime, JBoss does not create a queue object by itself. Therefore, you need to manually configure the queue object. You can create a xxx-service.xml file in the <jboss5.x installation directory>/Server/default/deploy directory, where xxx can take any value, but must be suffixed with "-service", for example, abc-service.xml. This file can be stored in deploy or its subdirectory (which can be a multi-layer subdirectory. The content of this file is as follows:

 
 
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <server> 
  3.     <mbean code="org.jboss.mq.server.jmx.Queue" name="jboss.mq.destination:service=Queue,name=jms"> 
  4.         <depends optional-attribute-name="DestinationManager"> 
  5.             jboss.mq:service=DestinationManager</depends> 
  6.     </mbean> 
  7. </server> 

<Mbean> the name attribute value of an element must be JMS, which must be consistent with the/section following queue/JMS.

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.