`
VerRan
  • 浏览: 459226 次
  • 性别: Icon_minigender_1
  • 来自: 陕西.西安
社区版块
存档分类
最新评论

JMS

阅读更多

The JMS API Programming Model

The basic building blocks of a JMS application consist of

Figure 33-5 shows how all these objects fit together in a JMS client application.

 

The JMS API Programming Model

 

Figure 33-5 The JMS API Programming Model

This section describes all these objects briefly and provides sample commands and code snippets that show how to create and use the objects. The last subsection briefly describes JMS API exception handling.

Examples that show how to combine all these objects in applications appear in later sections. For more details, see the JMS API documentation, which is part of the J2EE API documentation.

Administered Objects

Two parts of a JMS application--destinations and connection factories--are best maintained administratively rather than programmatically. The technology underlying these objects is likely to be very different from one implementation of the JMS API to another. Therefore, the management of these objects belongs with other administrative tasks that vary from provider to provider.

JMS clients access these objects through interfaces that are portable, so a client application can run with little or no change on more than one implementation of the JMS API. Ordinarily, an administrator configures administered objects in a JNDI namespace, and JMS clients then look them up by using the JNDI API. J2EE applications always use the JNDI API.

With the Application Server, you use the Admin Console to create JMS administered objects in the form of resources. You can also use the asadmin command.

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.

To learn how to use the Admin Console to create connection factories, see Creating JMS Administered Objects.

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.

For example, the following code fragment obtains an InitialContext object and uses it to look up a ConnectionFactory by name. Then it assigns it to a ConnectionFactory object:

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

In a J2EE application, JMS administered objects are normally placed in the jms naming subcontext.

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.

Creating destinations using the Application Server is a two-step process. You create a JMS destination resource that specifies the JNDI name of the destination. You also create a physical destination to which the JNDI name refers.

To learn how to use the Admin Console to create physical destinations and destination resources, see Creating JMS Administered Objects.

A JMS application can use multiple queues or topics (or both).

In addition to looking up a connection factory in a client program, you usually look up a destination. Unlike connection factories, destinations are specific to one domain or the other. To create an application that allows you to use the same code for both topics and queues, you cast and assign the destination to a Destination object. To preserve the semantics of queues and topics, however, you cast and assign the object to a destination of the appropriate type.

For example, the following line of code performs a JNDI lookup of the previously created topic jms/MyTopic and casts and assigns it to a Destination object:

The following line of code looks up a queue named jms/MyQueue and casts and assigns it to a Queue object:

With the common interfaces, you can mix or match connection factories and destinations. That is, in addition to using the ConnectionFactory interface, you can look up a QueueConnectionFactory and use it with a Topic, and you can look up a TopicConnectionFactory and use it with a Queue. The behavior of the application will depend on the kind of destination you use and not on the kind of connection factory you use.

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:

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.

Before your application can consume messages, you must call the connection's start method; for details, see Message Consumers. If you want to stop message delivery temporarily without closing the connection, you call the stop method.

Sessions

A session is a single-threaded context for producing and consuming messages. You use sessions to create message producers, message consumers, and messages. Sessions serialize the execution of message listeners; for details, see Message Listeners.

A session provides a transactional context with which to group a set of sends and receives into an atomic unit of work. For details, see Using JMS API Local Transactions.

Sessions implement the Session interface. After you create a Connection object, you use it to create a Session:

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. (For more information, see Controlling Message Acknowledgment.)

To create a transacted session, use the following code:

Here, the first argument means that the session is transacted; the second indicates that message acknowledgment is not specified for transacted sessions. For more information on transactions, see Using JMS API Local Transactions. For information about the way JMS transactions work in J2EE applications, see Using the JMS API in a J2EE Application.

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); 

You can create an unidentified producer by specifying null as the argument to createProducer. With an unidentified producer, you do not specify a destination until you send a message.

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

You must first create the messages; see Messages.

If you created an unidentified producer, use an overloaded send method that specifies the destination as the first parameter. For example:

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. For details, see Creating Durable Subscriptions.

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. (Remember always to call the start method; forgetting to start the connection is one of the most common JMS programming errors.)

You 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, described in Message Listeners.

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:

After you register the message listener, you call the start method on the Connection to begin message delivery. (If you call start before you register the message listener, you are likely to miss messages.)

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 (see Message Bodies).

A message listener is not specific to a particular destination type. The same listener can obtain messages from either a queue or a topic, depending on the type of destination for which the message consumer was created. A message listener does, however, usually expect a specific message type and format. Moreover, if it needs to reply to messages, a message listener must either assume a particular destination type or obtain the destination type of the message and create a producer for that destination type.

Your onMessage method should handle all exceptions. It must not throw checked exceptions, and throwing a RuntimeException is considered a programming error.

The session used to create the message consumer serializes the execution of all message listeners registered with the session. At any time, only one of the session's message listeners is running.

In the J2EE platform, a message-driven bean is a special kind of message listener. For details, see Using Message-Driven Beans.

Message Selectors

If your messaging application needs to filter the messages it receives, you can use a JMS API message selector, which allows a message consumer to specify the messages it is interested in. Message selectors assign the work of filtering messages to the JMS provider rather than to the application. For an example of an application that uses a message selector, see A J2EE Application That Uses the JMS API with a Session Bean.

A message selector is a String that contains an expression. The syntax of the expression is based on a subset of the SQL92 conditional expression syntax. The message selector in the example selects any message that has a NewsType property that is set to the value 'Sports' or 'Opinion':

The createConsumer and createDurableSubscriber methods allow you to specify a message selector as an argument when you create a message consumer.

The message consumer then receives only messages whose headers and properties match the selector. (See Message Headers, and Message Properties.) A message selector cannot select messages on the basis of the content of the message body.

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, allowing you to create messages that match formats used by non-JMS applications on heterogeneous platforms.

A JMS message has three parts: a header, properties, and a body. Only the header is required. The following sections describe these parts:

For complete documentation of message headers, properties, and bodies, see the documentation of the Message interface in the API documentation.

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. Table 33-1 lists the JMS message header fields and indicates how their values are set. 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.

 

Message Properties

You can create and set properties for messages if you need values in addition to those provided by the header fields. You can use properties to provide compatibility with other messaging systems, or you can use them to create message selectors (see Message Selectors). For an example of setting a property to be used as a message selector, see A J2EE Application That Uses the JMS API with a Session Bean.

The JMS API provides some predefined property names that a provider can support. The use either of these predefined properties or of user-defined properties is optional.

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. Table 33-2 describes these message types.

Table 33-2 JMS Message Types 
Message Type
Body Contains
TextMessage
A java.lang.String object (for example, the contents of an Extensible Markup Language file).
MapMessage
A set of name-value pairs, with names as String objects and values as primitive types in the Java programming language. The entries can be accessed sequentially by enumerator or randomly by name. The order of the entries is undefined.
BytesMessage
A stream of uninterpreted bytes. This message type is for literally encoding a body to match an existing message format.
StreamMessage
A stream of primitive values in the Java programming language, filled and read sequentially.
ObjectMessage
A Serializable object in the Java programming language.
Message
Nothing. Composed of header fields and properties only. This message type is useful when a message body is not required.

 

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:

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:

Exception Handling

The root class for exceptions thrown by JMS API methods is JMSException. Catching JMSException provides a generic way of handling all exceptions related to the JMS API. The JMSException class includes the following subclasses, which are described in the API documentation:

All the examples in the tutorial catch and handle JMSException when it is appropriate to do so.

评论

相关推荐

    javax.jms.jar

    Classes contained in javax.jms.jar: javax.transaction.xa.XAResource.class javax.jms.BytesMessage.class javax.jms.Message.class javax.jms.JMSException.class javax.jms.Destination.class javax.jms....

    PDS-17001_JMS583_Datasheet_(Rev._1.0)_JMS583_jmicron_jms583开发_

    **JMS583芯片详解** JMS583是一款由JMicron科技公司设计的高性能USB 3.1 Gen 2至PCIe Gen3x2桥接芯片,旨在为存储设备提供高速数据传输能力。这款芯片是针对现代数据密集型应用而优化的,如SSD固态硬盘和外部存储...

    java.jms.jar JMS需要的JAR包

    `javax.jms.jar` 文件中包含了如`javax.jms.Queue`, `javax.jms.Topic`, `javax.jms.MessageProducer`, `javax.jms.MessageConsumer`, `javax.jms.ConnectionFactory`等关键接口,以及其他辅助类和异常类,开发者...

    jms-1.1.jar(jms工具jar包)

    Java消息服务(Java Message Service,简称JMS)是Java平台中用于企业级应用间异步通信的标准接口。它提供了一种可靠的消息传递机制,允许应用程序创建、发送、接收和读取消息。`jms-1.1.jar` 是一个包含了JMS 1.1...

    javax.jms包,sun的JMS接口规范包

    Java消息服务(Java Message Service,简称JMS)是Java平台中用于企业级应用集成的API,它定义了一组标准接口,允许应用程序创建、发送、接收和读取消息。`javax.jms`包是JMS规范的核心部分,包含了各种与消息传递...

    JMS583 USB PCIE 桥接芯片方案

    **JMS583 USB转PCIE桥接芯片方案** JMS583是一款由JMicron科技公司设计的高效能USB到PCI Express (PCIe)桥接芯片,旨在为电子设备提供一种灵活的方式来实现高速数据传输。这款芯片能够将USB接口转换成PCIe接口,以...

    jms-1.1.jar

    《JMS 1.1 API详解与应用实践》 Java消息服务(Java Message Service,简称JMS)是Java平台中用于企业级应用间异步通信的一种标准接口。JMS 1.1是其一个重要的版本,它为分布式系统中的应用程序提供了一种可靠的...

    USB转SATA硬盘盒JMS583量产工具

    标题中的“USB转SATA硬盘盒JMS583量产工具”是指一种专门用于将USB接口转换为SATA接口的硬件设备,其中JMS583是该转换器的主控芯片。这种硬盘盒允许用户将传统的SATA硬盘通过USB接口连接到电脑上,方便数据迁移、...

    JMS583量产工具.zip

    【JMS583量产工具】是一款专门针对JMS583芯片进行批量生产操作的软件工具,主要用于USB闪存盘的制作与修复。这款工具的全称可能为"JMS583 Mass Production Tool",它允许用户一次性对多个JMS583芯片驱动的USB设备...

    javax.jms.jar下载

    javax.jms.BytesMessage.class javax.jms.Connection.class javax.jms.ConnectionConsumer.class javax.jms.ConnectionFactory.class javax.jms.ConnectionMetaData.class javax.jms.DeliveryMode.class javax.jms....

    JMS1.1规范(中文)

    Java消息服务(Java Message Service,简称JMS)是Java平台中用于企业级应用集成的API,主要用于在分布式环境中传递消息。JMS1.1规范是该API的一个版本,提供了标准接口,使得不同的消息中间件(Message Oriented ...

    USB3.0移动硬盘盒 JMS578 固件2018最新固件, G-Technology 移动硬盘盒固件 for JMS578

    标题中的“USB3.0移动硬盘盒 JMS578 固件2018最新固件, G-Technology 移动硬盘盒固件 for JMS578”揭示了这个压缩包文件主要关注的是一个特定型号的USB3.0移动硬盘盒,该盒子采用JMS578主控芯片,并且提供了2018年...

    javax.jms-1.1.jar

    `javax.jms-1.1.jar` 是一个Java Message Service(JMS)的API库,它属于Java标准版(Java Standard Edition, Java SE)的一部分。JMS是Java平台上的一个规范,用于在分布式环境中进行异步消息传递。这个库主要用于...

    JMS578多达13个固件打包升级工具包 可修改休眠时间

    文件包含: 13个不同固件 两个固件升级工具 其中一个是量产工具可以修改休眠时间和盒子信息 TRIM检查工具 有几个固件版本为全网首发,别人没有的资源 固件列表: JMS578_00.01.00.05 ...JMS578_254.02.03.09_NoUAS

    weblogic中使用JMS发送和接受消息

    WebLogic Server是一款由Oracle公司提供的企业级应用服务器,它支持Java Message Service (JMS) 规范,允许在分布式环境中可靠地发送和接收消息。JMS是Java平台上的标准接口,用于实现应用程序间的异步通信。本文将...

    Weblogic JMS 依赖jar包下载

    Weblogic JMS 依赖jar包是Oracle公司的中间件产品Weblogic Server中用于实现Java Message Service (JMS) 功能的关键组件。JMS是一种标准API,它允许应用程序在分布式环境中发送和接收消息,提供了异步通信的能力。在...

    JMS(JMS(JMS(JMS(

    JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS(JMS

    JMS577主控通刷固件

    标题“JMS577主控通刷固件”指的是针对希捷移动硬盘中采用JMS577主控芯片的固件更新解决方案。在IT领域,固件是存储在硬件设备上的软件部分,它控制设备的操作并提供与主机系统的交互。JMS577是一种常见的硬盘主控...

Global site tag (gtag.js) - Google Analytics