JMS 基础概念(二)

本节讲述:The JMS API Programming Model



上图为JMS Programming Model 的框架图


一、首先阐述上一篇文档的遗留问题:Administered Objects.

Administered Objects

    Two parts of a JMS application--destinations and connection factories--are best maintained administratively rather than programmatically . 【Administered Objects 是通过文件配置的,包含两部分destinations 和 connection factories】

    1.1 Connection Factories
    A connection factory is the object a client uses to create a connection to a provider. A connection factory encapsulates a set of connection configuration parameters that has been defined by an administrator. Each connection factory is an instance of the ConnectionFactory, QueueConnectionFactory, or TopicConnectionFactory interface.
  
    如下图:



     At the beginning of a JMS client program, you usually perform a JNDI lookup of a connection factory, then cast and assign it to a ConnectionFactory object.

    
     Context ctx = new InitialContext(); 
     ConnectionFactory connectionFactory = (ConnectionFactory)
     ctx.lookup("jms/ConnectionFactory"); 
     


     1.2 Destinations
     A destination is the object a client uses to specify the target of messages it produces and the source of messages it consumes. In the PTP messaging domain, destinations are called queues. In the pub/sub messaging domain, destinations are called topics.
   
    


    
     Destination myDest = (Destination) ctx.lookup("jms/MyTopic"); 
     Queue myQueue = (Queue) ctx.lookup("jms/MyQueue");
     


    
二、Connections
Connections

     A connection encapsulates a virtual connection with a JMS provider. A connection could represent an open TCP/IP socket between a client and a provider service daemon. You use a connection to create one or more sessions.

     Connections implement the Connection interface. When you have a ConnectionFactory object, you can use it to create a Connection:
   
Connection connection = connectionFactory.createConnection(); 

     Before an application completes, you must close any connections that you have created. Failure to close a connection can cause resources not to be released by the JMS provider.Closing a connection also closes its sessions and their message producers and message consumers.

    
connection.close(); 

     Before your application can consume messages, you must call the connection's start method.

三、Sessions
Sessions
     A session is a single-threaded context for producing and consuming messages. You use sessions to create message producers, message consumers, and messages.
     A session provides a transactional context with which to group a set of sends and receives into an atomic unit of work.
     Sessions implement the Session interface. After you create a Connection object, you use it to create a Session:
    
Session session = connection.createSession(false, 
  Session.AUTO_ACKNOWLEDGE);


     The first argument means that the session is not transacted; the second means that the session automatically acknowledges messages when they have been received successfully.
     To create a transacted session, use the following code:
    
Session session = connection.createSession(true, 0); 


四、Message Producers
     A message producer is an object that is created by a session and used for sending messages to a destination. It implements the MessageProducer interface.
     You use a Session to create a MessageProducer for a destination. Here, the first example creates a producer for the destination myQueue, and the second for the destination myTopic:

    
     MessageProducer producer = session.createProducer(myQueue); 
     MessageProducer producer = session.createProducer(myTopic); 
     

     After you have created a message producer, you can use it to send messages by using the send method:
    
producer.send(message); 


五、Message Consumers

    A message consumer is an object that is created by a session and used for receiving messages sent to a destination. It implements the MessageConsumer interface.
    A message consumer allows a JMS client to register interest in a destination with a JMS provider. The JMS provider manages the delivery of messages from a destination to the registered consumers of the destination.
    For example, you use a Session to create a MessageConsumer for either a queue or a topic:
   
MessageConsumer consumer = session.createConsumer(myQueue); 
MessageConsumer consumer = session.createConsumer(myTopic); 

    You use the Session.createDurableSubscriber method to create a durable topic subscriber. This method is valid only if you are using a topic.

    After you have created a message consumer, it becomes active, and you can use it to receive messages. You can use the close method for a MessageConsumer to make the message consumer inactive. Message delivery does not begin until you start the connection you created by calling its start method.
    ou use the receive method to consume a message synchronously. You can use this method at any time after you call the start method:
   
connection.start();
Message m = consumer.receive(); 
connection.start();
Message m = consumer.receive(1000); // time out after a second 

     To consume a message asynchronously, you use a message listener.
    
Message Listeners
     A message listener is an object that acts as an asynchronous event handler for messages. This object implements the MessageListener interface, which contains one method, onMessage. In the onMessage method, you define the actions to be taken when a message arrives.
     You register the message listener with a specific MessageConsumer by using the setMessageListener method. For example, if you define a class named Listener that implements the MessageListener interface, you can register the message listener as follows:
    
Listener myListener = new Listener();
consumer.setMessageListener(myListener); 


     After you register the message listener, you call the start method on the Connection to begin message delivery.
     When message delivery begins, the JMS provider automatically calls the message listener's onMessage method whenever a message is delivered. The onMessage method takes one argument of type Message, which your implementation of the method can cast to any of the other message types.
    
六、Messages
     The ultimate purpose of a JMS application is to produce and to consume messages that can then be used by other software applications. JMS messages have a basic format that is simple but highly flexible.
     A JMS message has three parts: a header, properties, and a body. Only the header is required.

     6.1 Message Headers
     A JMS message header contains a number of predefined fields that contain values that both clients and providers use to identify and to route messages. For example, every message has a unique identifier, which is represented in the header field JMSMessageID. The value of another header field, JMSDestination, represents the queue or the topic to which the message is sent. Other fields include a timestamp and a priority level.
     Each header field has associated setter and getter methods, which are documented in the description of the Message interface. Some header fields are intended to be set by a client, but many are set automatically by the send or the publish method, which overrides any client-set values.

    


     6.2 Message Bodies
     The JMS API defines five message body formats, also called message types, which allow you to send and to receive data in many different forms and provide compatibility with existing messaging formats.

    


     The JMS API provides methods for creating messages of each type and for filling in their contents. For example, to create and send a TextMessage, you might use the following statements:
    
TextMessage message = session.createTextMessage();
message.setText(msg_text);     // msg_text is a String
producer.send(message); 


      At the consuming end, a message arrives as a generic Message object and must be cast to the appropriate message type. You can use one or more getter methods to extract the message contents. The following code fragment uses the getText method:
     
Message m = consumer.receive(); 
if (m instanceof TextMessage) {
  TextMessage message = (TextMessage) m;
  System.out.println("Reading message: " + message.getText());
} else {
  // Handle error
} 

    
      至于整个的流程和例子,以及JSM的优缺点会在后续的文章中给出.
    

猜你喜欢

转载自fay19880111-yeah-net.iteye.com/blog/1637299
jms