Upload
trinhthuan
View
227
Download
0
Embed Size (px)
Citation preview
2
2
Sang [email protected]
www.javapassion.com/j2ee
Technology EvangelistSun Microsystems, Inc.
12/15/2004
3
3
Disclaimer & Acknowledgments? Even though Sang Shin and Sameer Tyagi are full-time
employees of Sun Microsystems, the contents here are created as their own personal endeavor and thus does not reflect any official stance of Sun Microsystems.
? Sun Microsystems is not responsible for any inaccuracies in the contents.
? Acknowledgments– "Some slides are made from the contents of the book Applied
"Enterprise JavaBeans Technology written by Kevin Boone (Sun Microsystems)
– Some slides are made from the contents of J2EE 1.4 Tutorial JMS section
12/15/2004
4
4
Revision History? 03/02/2003: version 1 Draft (Sameer)? 03/07/2002: version 2 Draft with speaker notes (Sameer)? 03/08/2003: version 3 Added code examples (Sameer)? 07/02/2003: version 4 Revised (Sang Shin)? 12/15/2004: version 5 Revised – reliable JMS messaging slides are added (Sang Shin)
12/15/2004
5
5
Agenda
? What is Messaging?– Messaging models, Reliability, Transaction,
Distributed messaging, Security
? Why Messaging?? What is JMS?? Architecture of JMS? JMS Programming APIs? Steps for writing JMS clients (sender and
receiver)? JMS and EJB (MDB)
This is the agenda of this session. First , we will spend some time understanding basic concept of enterprise messaging talking about two messaging models, reliability, transaction, distributed messaging, and security. Then we will talk about benefits of using messaging. Then in the 2nd part of this presentation, we will spend time talking about JMS, Java Messaging Service starting with what JMS is and then architecture of JMS. We will then talk about programming APIs then we will go through steps for writing JMS application both sender and receiver sides. And at the end we will talk about how JMS and Message Driven Bean (MDB) are related.
12/15/2004
6
6
What is Messaging?
Messaging has been around for quite a while even before JMS as a way to build reliable, flexible, and scalable communication system. Some of you might have heard the term, Message-Oriented-Middleware, or MOM in short. In fact, in the mainframe world, product like IBM’s MQ_Series has been around for quite a while.
Now before we talk about JMS in detail, let’s talk about the concept of messaging and get some sense of what it is and why you want to use it and when you want to use it.
12/15/2004
7
7
Messaging System Concepts
? De-coupled (Loosely-coupled) communication? Asynchronous communication? Messages are the means of communication
between applications.? Underlying messaging software provides
necessary support – MOM (Message Oriented Middleware), Messaging
system, Messaging server, Messaging provider, JMS provider: they all mean this underlying messaging software
Messaging enables de-coupled communication. Sometimes it is called loosely-coupled communication. It is an de-coupled communication in that the sender does not have to know the details of the receiver, for example, the sender does not have to know whether a receiver is a live process or not or the location information of it such as IP address or port number. Instead the sender and receiver of messages communicate via an intermediary communication framework called messaging system. This is a departure from tightly-coupled communication systems such as RPC, socket, or RMI in which the communicating parties are talking each other directly instead of through a intermediary server. In this sense, messaging server functions like a central post office.
It is also asynchronous in that a sender of a message does not have to wait for an acknowledgment from the receiver and the receiver can be notified when there is a message to be dealt with. And because the sender and receiver are de-coupled, the only means of communication is via sending and receiving messages.
I mentioned that under the model of de-coupled communication, there is an intermediary communication framework called messaging system. And it is this underlying messaging system, by playing a role of central post office, that provides necessary support so that applications can send or receive messages. In this talk, I will use the terms, MOM, messaging system, messaging service provider, messaging server, interchangeably. Under JMS context, they are also called as JMS provider. In any case, they all refer to a server that provides the messaging framework.
12/15/2004
8
8
Messaging System Features
? Support of two messaging models – Point-to-point– Publish/Subscribe
? Reliability? Transactional operations? Distributed messaging? Security
Now I would like to talk about some of the key features of a typical messaging system. And they include support of two messaging models - point-to-point and publish and subscribe -, how to handle reliable message delivery, transactional operations, distributed messaging, and security.
12/15/2004
9
9
Additional Features
? Some Messaging System vendors support– Guaranteed real-time delivery– Secure transactions– Auditing– Metering– Load balancing
In addition the basic messaging features of creating, sending and receiving messages, some messaging system support extra features such as guaranteed real-time delivery, secure transaction, auditing, metering, and load balancing. By the way, some of these features are beyond the scope of JMS specification. For example, load-balancing, auditing and metering, even security schemes are implementation specific issues. In fact, messaging system vendors will compete among themselves in these areas.
12/15/2004
11
Messaging Models
? Point to Point– A message is consumed by a single
consumer
? Publish/Subscribe– A message is consumed by multiple
consumers
There are two messaging models: Point-to-Point and Publish-and-Subscribe. Not all message vendors implement both. And as we will see later on, JMS defines distinct APIs for these two messaging models.We will talk about each of these two messaging models in a bit more detail in the following slide. But the main difference between the two models is that in point-to-point model, a message is consumed by a single consumer while in publish/subscribe model, a message is consumed by multiple consumers.
12/15/2004
12
Point-to-Point
? A message is consumed by a single consumer
? " "Destination of a message is a named queue
? First in, first out (at the same priority level)? Sender (producer) sends a message to
a named queue (with a priority level)? Receiver (consumer) extracts a message
from the queue
As was mentioned, under point-to-point model, a message is consumed by a single consumer. And destination of a message is a named queue (as opposed to a topic under pub/sub messaging model). It is basically first in and first out model in that the message is queued will be the one that will be taken out first assuming they are at the same priority level.
Under Point-to-point model, sender sends a message to a named queue with a priority level and then receiver extracts a message from the queue.
12/15/2004
13
Point-to-Point
QueueClient
Senders SendsConsumes
Acknowledges
Client Receiver
Receives messages on Receives messages on the queuethe queue
Posts messages to the Posts messages to the queuequeue
A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire.
12/15/2004
14
When to use Point-to-Point?
? Use it when every message you send must be processed successfully by one consumer
So when do you want to use point-to-point messaging model? You want to use it when every message you send must be processed successfully by one consumer.
12/15/2004
15
Publish/Subscribe (Pub/Sub)? A message is consumed by multiple
consumers? " "Destination of a message is a named topic
? not a queue
? Producers “publish” to topic? Consumers “subscribe” to topic
In publish/subscribe model, a message can be consumed by multiple consumers. Destination of a message is a named topic. A topic does not work like a queue in that messages in a topic are not typically queued. Instead, each new message in the topic will overwrite any existing message.
So under pub/sub messaging model, producers or senders publish to a topic and then consumers subscribes to a topic.
12/15/2004
16
Publish-and-Subscribe
ClientSender Sends
Consumes
Acknowledges
Client Receiver
Client Publisher Publishes
Delivers
Subscribes
Topic
SubscribesClient
subscriber
Delivers
Client subscriber
Client Publisher Topic
Client subscriber
Client subscriber
Publishes
Subscribes
Delivers
Subscribes
Subject of Subject of communicationcommunication
Available to registered Available to registered participantsparticipants
DeliversPosts messages to the
topic
Receives messages on the topic
In publish/subscribe model, publishers (senders) and subscribers (receivers) are generally anonymous and may dynamically publish or subscribe to the content hierarchy. The messaging system takes care of distributing the messages arriving from a topic's multiple publishers to its multiple subscribers.
Pub/sub messaging has the following characteristics: •Each message may have multiple consumers. •There is a timing dependency between publishers and non-durable subscribers, because a client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages. •The JMS API relaxes this timing dependency to some extent by allowing clients to create durable subscriptions. Durable subscriptions can receive messages sent while the subscribers are not active. Durable subscriptions provide the flexibility and reliability of queues but still allow clients to send messages to many recipients.
12/15/2004
17
When to use Pub/Sub?
? Use it when a message you send need to be processed by multiple consumers
? Example: HR application– Create “new hire” topic– Many applications (“facilities”, “payroll”, etc.)
subscribe “new hire” topic
Because there could be multiple publishers and multiple consumers to a same topic, Pub/sub model is especially useful in situations in which a group of programs want to notify each other of a particular event.
For example, the HR system could publish a message indicating a new hire to a topic called “NewHire”. All of the applications that want to receive a notification when a new person is hired would subscribe to the “NewHire” topic. Through this subscription, the financial application could use the notification to update the payroll database, and the facilities system could generate a new phone number and so on.
12/15/2004
18
18
Reliability
Now let's talk about how a typical messaging system handles reliability.
12/15/2004
19
19
Reliability
? Some guarantee of delivery of a message– Different degree of reliability is possible– Sender can specify different level of reliability– Higher reliability typically means less throughput
? Typically uses persistent storage for preserving messages
Reliability under messaging system context means some guarantee of delivery of messages. Of course, there could be different degree of reliability. Typical messaging systems allow sender to specify the level of reliability. Typically higher reliability comes at the expense of throughput.
Now in order to achieve higher level of reliability, messaging systems typically use persistent storage.
12/15/2004
20
20
TransactionalOperations
Now let's talk about transactional support of typical enterprise messaging systems.
12/15/2004
21
Transactional Operations
? Transactional production– Sender groups a series of messages into a
transaction
– Either all messages are enqueued successfully or none are
? Transactional consumption– Consumer retrieves a group of messages as a
transaction– Unless all messages are retrieved successfully,
the messages remain in a queue or topic
Now under the context of a messaging system, transactional operations occur at either producer or consumer side but at both ends at the same time. Let's call them transactional production and transactional consumption.
Transactional production means a sender groups a series of messages into a single transaction, in which either all messages are enqueued successfully or none are.
On a consumer side, transactional consumption means that consumer retrieves a group of messages as a single transaction. And unless all messages are retrieved successfully, the messages will remain in a queue or topic so that the consumer can try to get them later on.
12/15/2004
22
Transactional Scope
? Client-to-Messaging system scope– Transaction encompasses the interaction
between each messaging client (applications) and the messaging system
– JMS supports this
? Client-to-Client scope– Transaction encompasses both clients– JMS does not support this
Now let's talk about transactional scope a bit. In a typical enterprise messaging system, there could be two different transactional scopes: client to messaging system scope and client to client scope. The former encompasses only the interaction between the messaging client and the messaging system while the latter encompasses end client to end client operations. Now one thing to note is JMS supports only the former.
12/15/2004
23
Client-to-Messaging SystemTransactional Scope
Application 1 Queue Application 2
Messaging system
source: Applied Enterprise JavaBeans[1]
This picture shows the client to messaging system transactional scopes. The eclipse on the left side shows transactional scope between the sender and messaging system while the one on the right side shows transactional scope between messaging system and receiver.
12/15/2004
24
Client-to-Client Transactional Scope
Application 1 Queue Application 2
Messaging system
source: Applied Enterprise JavaBeans[1]
This picture shows client to client transactional scope. Again, this is not supported by JMS.
12/15/2004
25
25
DistributedMessaging
A quick note on distributed messaging on a typical enterprise messaging system.
12/15/2004
26
Distributed Messaging
? Enterprise messaging systems might provide an infrastructure in which messages are being forwarded between servers
– called “message channel”
Typical enterprise messaging systems provide an infrastructure in which messages are being forwarded between servers. And this is called message channel.
12/15/2004
27
Distributed Messaging
Application 1
Application 2
message
Queue
Queue
Messaging server 2
Messaging server 1
Message channel
message
source: Applied Enterprise JavaBeans[1]
This picture shows the distributed messaging. In this picture, application 1 puts messages into the queue allowing application 2 to retrieve them.
12/15/2004
28
28
Security
Now let's talk about how typical enterprise messaging systems handle security.
12/15/2004
29
Security Issues
? Authentication– Messaging systems typically require clients to
present signed certificates
? Confidentiality of messages– Messaging system typically provide encryption
? Data integrity of messages– Messaging system typically provide data
integrity through message digest
? Security is currently handled in vendor-specific way
The security issues that need to be addressed by messaging systems include authentication. Typically messaging systems require their clients to present signed certificates in order to perform authentication.
As for confidentiality, a messaging system might encrypt the data in a message before it send it out. As for data integrity, a messaging system might use message digest.
Final note on security. Currently, security is handled in vendor specific way. Given that a messaging client can interoperate only with clients running over the same messaging system anyway, this is not really a problem.
12/15/2004
31
31
Why Messaging?
? Platform independence? Network location independence? Works well in heterogeneous environments
Now we have several slides talking about the benefits of using messaging systems. First, platform independence. Because the communication between applications are through messages, any platform that can generate valid messages can participate in the communication regardless of its platform differences from others. That is, it does not matter which programming language you use to generate the message. It does not matter which operating system or processor architecture your application is running.
Next, network location independence. Because the sender of the message sends messages to an abstracted destination through the intermediary messaging server, the sender does not have to know the concrete location details of the receiver such as hostname, IP address or port number, and this is different from other communication models such as RPC, socket, or RMI in which the communicating parties have to know the concrete location of each other before any communication gets started. In messaging, it is the job of the messaging server not the sender to figure out the concrete location of the receiver.
Scalability. Because, under messaging system, every communication is done through a central messaging server, it is a lot easier to accommodate higher number of clients. That is, in order to accommodate higher number of clients, you can just increase the hardware capacity of the messaging server without requiring any change in your application or any fundamental change in the architecture.
Messaging also works well under heterogeneous environment where different types of applications running on different platforms have to communicate each other because again the only agreement they have to have is valid messages. That is why, messaging systems are quite popular in the space of enterprise application integration.
12/15/2004
32
32
Why Messaging?
? Anonymity– Who doesn’t matter– Where doesn’t matter– When doesn’t matter
? Contrast with RPC-based systems– CORBA– RMI
We touched upon anonymity a bit already in the previous slides. What we mean by anonymity is the decoupled nature of the communication under messaging system. For example, the sender does not have to know who the receiver is, It does not have to know where the receiver resides. The sender does not have to know when the receiver is going to receive the message. In other words, the sender sends a message with an assumption that sometime, someone, somewhere will take the message and do something about it. This model is a contrast to RPC or socket based communication system where communicating parties know each other precisely in order to have a successful communication.
12/15/2004
33
33
Why Messaging?
? Scalability– Handle more clients with
? No change in the application? No change in the architecture? No degradation in system throughput
– Increase hardware capacity of messaging system if higher scalability is desired
What is scalability? Scalability means that the messaging system should be able accommodate higher number of clients without requiring any change in your application nor in the infrastructure. In other words, in a scalable system, accommodating higher number of clients without sacrificing throughput should be just a matter of adding more hardware in the middle. That is, if there are more clients to be dealt with, just increase the capacity of the messaging system in the middle. There is no change required in your application or architectural model.
Current messaging systems out there have been around for quite a while and typical implementation can handle tens of thousands of clients and tens of thousands of events per second.
12/15/2004
34
34
Why Messaging?
? Robustness– Receivers can fail.– Senders can fail.– Network can fail.– Messaging System continues to function.
Roboutness means that the system still should work even if there is some partial failure somewhere in the network. That is, the partial failure should be contained to the location where the failure occurs not break down the whole network. Failures can occur anytime in any point on the network. It is fact of life. The messaging system can continue to function despite these various failures. For example, if there is a failure in the receiver, the messages that are to be delivered to that receiver will be persistently maintained by the messaging server until the receiver is ready to receive them. If a sender fails, it should not affect the way the receiver behaves. And it is this robustness of the messaging system that make it popular in mission-critical, 24 x7 enterprise environment.
Because the messaging system handles partial failure without bringing down the whole nework, there is no single point of failure. Now some of you might ask “Hmm. Wait a minute! The message server looks like a perfect candidate for single point of failure.” Well, when we are talking about a message server, we are talking about more from an conceptual level. Typically messaging system vendors have implementations that are fault-tolerant.
12/15/2004
36
36
Messaging Applications
? Credit card transactions? Weather reporting? Workflow? Network management? Supply chain management? Customer care? Communications (Voice Over IP,
Paging Systems, etc.)? Many more
What are the types of applications you can build with messaging system? This slide shows the list of applications you can build with messaging system. Basically it includes every type of vertical application that can leverage the flexibility, robustness, scalability of the model of de-coupled communication.
Now some of you might be saying - “ Yeah, messaging sounds great. It provides scalability, flexibility, location independence, and other good stuff. Should I use messaging for all my applications instead of RMI or other tightly coupled communication model?” The answer is “Of course not”. Just like any good thing in life, there is is a cost involved. And in the messaging model, the cost is you have to have messaging system. And your decision to use which model really depends on the nature and requirement of your applications. For example, if you want to talk to your Oracle database which is located with highly reliable internal network and your application knows exactly the location of the Oracle server and the Oracle server itself is fault-tolerant and scalable, you probably don’t need to add the messaging abstraction in the middle of that relationship. The time the messaging is useful is when you want to separate the destination or networking from your code . For example, if you are building supply chain management application and it have to deal with multiple 3rd-party suppliers which are always in change and the communication with them have to be done over unreliable internet and you don’t want to deal with them individually in your application, messaging certainly could provide a value.
12/15/2004
37
37
What is JMS?
OK. We spent some time looking into what enterprise messaging system is and why people want to use it. Now the rest of this session is devoted to JMS. First, let's talk about what JMS is first.
12/15/2004
38
38
What is JMS?
? JMS is a set of Java interfaces and associated semantics (APIs) that define how a JMS client accesses the facilities of a messaging system
? Supports message production, distribution, delivery
? Supported message delivery semantics – Synchronous or Asynchronous– transacted – Guaranteed– Durable
JMS is basically a set of Java interfaces and their associated semantics that define how a JMS client accesses the facilities of a messaging system. By the way, I am going to use the terms JMS client and JMS applications interchangeably in this presentation.
JMS APIs handle message production, distribution, and delivery. And the message delivery semantics include both synchronous and asynchronous message delivery, transacted message delivery, guaranteed and durable message delivery.
12/15/2004
39
39
What is JMS? (Continued)
? Supports existing messaging models– Point-to-Point (reliable queue)– Publish/Subscribe
? Message selectors (on the receiver side)? 5 Message types
JMS supports two messaging models we talked about. JMS also deals support message selectors so that a JMS client can receive messages based on a selection criteria. JMS also defines 5 message types.
12/15/2004
40
40
JMS is an API
Java™ Application
JMS API
JMS Provider
IBMMQSeries
JMS Provider
ProgressSonicMq
JMS Provider
Fiorano
JMS Provider
JMS Provider
BEA SUN MQ
JMS is a standard Java programming API for using the facilities of underlying messaging systems in the same sense that JDBC is a standard Java programming API for accessing relational database. Each messaging system has its own JMS provider that supports JMS API that can be used by JMS application (JMS client).
12/15/2004
41
JMS and J2EE? Allows Java Developers to access the power of messaging systems? Part of the J2EE Enterprise Suite
JMSJMS
Now how does JMS, Java Message Service, fit in the big picture of J2EE?
As was mentioned in the previous slide, JMS is simply a Java interface to the messaging service. What is it for? Again, for the same reason JDBC was introduced to provide standard APIs for accessing various types of SQL servers, JMS was introduced to facilitate the “portability of you code” over various messaging systems.
JMS is now part of J2EE enterprise suite. That is, your application can now fully leverage the power of messaging system of any J2EE compliant platform with again portability of your code guaranteed.
Besides your JMS applications can take advantage of other enterprise features of J2EE such as transaction support or JNDI naming and directory service.
12/15/2004
42
JMS Design Goals
? Consistency with existing APIs? Independence from Messaging
system provider? Minimal effort on part of Messaging
system provider? Provide most of the functionality
of common messaging systems? Leverage Java technology
What are the design goals of JMS? First, to provide rather consistent Java messaging APIs with existing messaging APIs. This will make smooth migration of existing applications to JMS applications.
Independence from messaging system provider. This goal is not much different from other Java API initiatives. From programmer’s perspective, you can develop your application without tying yourself with a particular messaging system. From deployer’s perspective, different messaging systems can be plugged into without affecting the applications. From the messaging system provider’s perspective, they can evolve their product independently and without forcing any change in their client’s application. The JMS is also designed to accommodate most of the existing messaging systems with minimum effort on their part. That is, it should be relatively easy for messaging system vendors to convert their products to be JMS compliant. In fact in most of the cases, it should be just a matter of putting Java wrappers to their existing systems.
Another design goal of JMS is to provide the most of the relevant messaging functions that are available in existing messaging systems.
And again because it is based on Java, it does enjoy all those benefits that are inherent in the Java technology such as cross platform support.
12/15/2004
43
43
Architecture ofa JMS Application
Now let's talk about architecture of a JMS application.
12/15/2004
44
JMS Architectural Components
? JMS clients? Non-JMS clients? Messages? JMS provider (Messaging systems)? JNDI administered objects
– Destination– ConnectionFactory
Now let’s take a look at typical JMS application environment. A typical JMS application is composed of the following parts:
-JMS Clients - These are the Java language programs that send and receive messages. These are the programs you write.-Non-JMS Clients - These are clients that use a message systems native client API instead of JMS. If the application predated the availability of JMS it is likely that it will include both JMS and non-JMS clients.-Messages - Each application defines a set of messages that are used to communicate information between its clients.-JMS Provider - This is a messaging system that implements JMS interface in addition to the other administrative and control functionality required of a full featured messaging product.-Administered Objects - Administered objects are pre-configured JMS objects created and registered to the JNDI by an administrator for the use of clients as we talked about in the previous slide. Again, JMS defines two JMS objects, destination object and connection factory object.
12/15/2004
45
Architecture of JMS Application
JMS Application(JMS Client)
JMS provider(vendor specific)
JMS API(vendor neutral)
Messaging service
JMS Application(JMS Client)
JMS provider(vendor specific)
JMS API(vendor neutral)
This picture shows architecture of JMS application. JMS application, which is sometimes called JMS clients, uses JMS API to use the facilities provided by JMS provider. JMS API is vendor neutral meaning JMS application that uses JMS API is portable over many messaging system. JMS provider is vendor specific over vendor specific messaging system. Again this is analogous to JDBC API, that is vendor neutral, which is implemented by vendor specific JDBC driver.
By the way, JMS clients can interoperate with non-JMS clients over a specific messaging service.
12/15/2004
46
JMS Terminology
? Domain (Messaging modes)? point-to-point, publish/subscribe
? Session? Connection? Destination? Produce, send, publish? Consume, receive, subscribe
Before we move on, let's talk about JMS terms a bit. JMS spec defines a term Domain to refer messaging models. A session is a set of interactions between JMS application and the messaging system that together constitute a transaction. A session object also acts a factory for message objects and for producers and consumer objects for a particular transaction.
A connection is a logical communication channel between JMS application and the messaging system. Several sessions may occur within one connection.
To “produce” is to place a message into a queue or a topic. “Production” is the general term for any messaging operation that provide new data. Adding new messages to a queue is normally referred to as “sending” while for a topic is “publishing”.
To “consume” is to remove messages from a queue or topic. To be able to consume from a topic, the client must first “subscribe”. Subscription may be durable or nondurable, as we will discuss later on.
12/15/2004
47
47
JMS Domains(Messaging Models)
We already talked about concept of messaging models. JMS specification calls these messaging models as Domains.
12/15/2004
48
JMS Domains (Messaging Styles)
? JMS Point-to-Point– Messages on a queue can be persistent or
non-persistent? JMS Pub/Sub
– Non-durable
– Durable
JMS supports point-to-point and publish/subscribe messaging models. The messages in a queue of point-to-point model can be either persistent or non-persistent.
JMS Pub/Sub messaging model supports both durable and nondurable message subsciptions.
12/15/2004
49
JMS Pub/Sub Non-durable vs. JMS Pub/Sub Durable? Non-durable
– Messages are available only during the time for which the subscriber is active
– If subscriber is not active (not connected), it will miss any messages supplied in its absence
? Durable– Messages are retained on behalf of subscribers
that are not available at the time the message was produced
Now let's talk a bit on Non-durable and durable message subscription under Pub/Sub messaging model.
Non-durable message subscription means that messages are available only during the time for which the subscriber is actively connected. If the subscriber is not active, it will miss any messages supplied in it absence.
Durable message subscription, on the other hand, means that messages are retained on behalf of subscribers that are not available at the time the message was produced.
12/15/2004
51
Messages
? Messages are the means of communication between messaging applications
? Actual on-the-wire Message formats vary widely among messaging systems
– A messaging system can interoperate with only with the same messaging system
As we talked about, Messages are the fundamental concept of any messaging system by being the point of communication between communicating applications. Consequently, Messages represent key abstraction under JMS.
Because the messaging systems have been implemented without any standard message format, there is a wide variation on message formats among messaging systems. And that is the fact of life and JMS is not trying to change that. That is, JMS is not trying to define on the wire message format should be.
What JMS tries to address is, by providing a unified and abstracted message model regardless of the underlying messaging systems, to guarantee the portability of your code. That is, instead of dictating what the message format is going to be, it specifies the APIs that you can use to construct the message.
12/15/2004
52
Message Java Interface
? JMS provides a unified and abstract message model via this interface
? Actual object implementation of this interface is provider specific
What JMS addresses is, by providing a unified and abstracted message model regardless of the underlying messaging systems through java.jms.Message interface, to guarantee the portability of your code. That is, instead of dictating what the message format is going to be, it specifies the APIs that you can use to construct the message.
12/15/2004
53
Message Components
? Header? Properties? Body
Message
Header
Properties
Body
The unified message model under JMS specifies that all messages be represented by objects that implement the Message Java interface type. And the Message interface separates a JMS message into three pieces- Header- Properties- Body
12/15/2004
54
Message Header
? Used for message identification and routing
? Includes Destination? Also includes other data:
– delivery mode (persistent, nonpersistent)
– message ID
– timestamp– priority– ReplyTo
All JMS messages support the same set of header fields. Header fields contain values used by both clients and providers to identify and route messages.
Among the header fields, the most significant field is “Destination” field which specifies the name of the queue for the point-to-point messaging model and name of the topic for the publish-and-subscribe model. We talked about the nature of the decoupled communication in which sender and receiver of the message do not have to know each other. Yet, the sender has to specify the destination somehow. The distinction of messaging system from the tightly couple system is that the destination is in an abstracted form of name of the queue or name of the topic instead of the concrete form of, for example, IP address or port number.
The other fields of the header include delivery mode such as persistent or non-persistent delivery. Message ID is a unique ID within a particular messaging system. Timestamp field specifies the time at which the message was sent. Priority field specifies the delivery priority of the message and ReplyTo field specifies destination to which the client expects responses to this message. Note that except the ReplyTo field, most of these fields are assigned by the messaging system.
12/15/2004
55
Message Header Fields
? JMSDestination ? JMSDeliveryMode
– persistent or nonpersistent? JMSMessageID? JMSTimeStamp? JMSRedelivered? JMSExpiration
This slide shows actual list of JMS message header fields.
12/15/2004
56
Message Header Fields
? JMSPriority? JMSCorrelationID? JMSReplyTo
– Destination supplied by a client; where to send reply
? JMSType– Type of message body
This is continuation of JMS message header fields.
12/15/2004
57
Message Properties
? Application-specific fields? Messaging system provider-
specific fields? Optional fields? Properties are Name/value pairs? Values can be byte, int, String, etc.
A message can also have arbitrary properties assigned to it in addition to the header fields. These properties might be application-specific or provider-specific. They are optional unlike header fields. Properties are basically name and value pairs and the values can be in various types such as byte, integer, or string.
12/15/2004
58
Message Body
? Holds content of message? Several types supported? Each type defined by a message
interface:– StreamMessage
– MapMessage
– TextMessage– ObjectMessage
– BytesMessage
Message body holds contents of the message. The type of content depends on message subtype. Currently JMS specification defines 5 message subtypes. We will look into each of these message body subtype in the following slides.
12/15/2004
59
Message Body Interfaces? StreamMessage:
– Contains Java primitive values
– Read sequentially
? MapMessage:– Holds name/value pairs– Read sequentially or by name
? BytesMessage– Uninterpreted bytes
– Used to match an existing message format
StreamMessage type uses a stream representation for its body. The stream holds self-describing sequence of Java primitive values. And they are read in sequential manner.
MapMessage type contains key-value pairs and can be read sequentially or by name.
ByteMessage type represents an uninterpreted stream of bytes. This type is used primarily for accessing legacy messaging systems and applications by matching existing message format.
12/15/2004
60
Example: Creating Text Message
? To create a simple TextMessage:
TextMessage message = session.createTextMessage();
message.setText("greetings");
So how do you create a text message? This code shows how to create a simple TextMessage. First, you create TextMessage object using session object and then set the actual text string by invoking setText() method of the TextMessage object.
12/15/2004
61
Example: Creating Object Message
? To create a simple ObjectMessage:
ObjectMessage message =session.createObjectMessage();
message.setObject(myObject);
NOTE: myObject must implement
java.io.Serializable
Creating an ObjectMessage is not that much different from one we just saw. You create an instance of ObjectMessage using a session object and then initialize it by invoking setObject() method. Note that because the object has to be transported over the network in a serialized form, it has to be the type of Serializable. Otherwise, an exception will occur.
12/15/2004
63
Destination Java Interface
? Represents an abstraction of topic or queue (not a receiver)
? Parent interface of Queue and Topic interfaces
Destination Java interface type represents an abstraction of a topic or a queue. Please note that Destination does not represent the JMS client on the other end. Destination interface is a parent interface of Queue and Topic Java interface.
12/15/2004
64
Destination Java Interface
Destination(from jms)
<<Interface>>
Topic
getTopicName() : StringtoString() : String
(from jms)
<<Interface>>Queue
getQueueName() : StringtoString() : String
(from jms)
<<Interface>>
This picture shows Destination Java interface.
12/15/2004
65
ConnectionFactory Java Interface? Factory class for creating a provider specific
connection to the JMS server? Analogous to the driver manager
(java.sql.DriverManager) in JDBC? Parent interface of QueueConnectionFactory
and TopicConnectionFactory interfaces
A ConnectionFactory is a factory class for creating a provider specific connection to JMS provider.
12/15/2004
66
ConnectionFactory Java Interface
ConnectionFactory(from jms)
<<Interface>>
QueueConnectionFactory
createQueueConnection()createQueueConnection()
(from jms)
<<Interface>>TopicConnectionFactory
createTopicConnection()createTopicConnection()
(from jms)
<<Interface>>
This picture shows the ConnectionFactory interface. Please note that the QueueConnectionFactory and TopicConnectionFactory extends ConnectionFactory interface.
12/15/2004
67
Connection Java Interface
? An abstraction that represents a single communication channel to JMS provider
? Created from a ConnectionFactory object ? A connection should be closed when the
program is done using it.
Connection Java interface represents an abstraction of a communication channel between JMS client and JMS provider. It is created from ConnectionFactory object. JMS application should close Connection object when it is done with it.
12/15/2004
68
Connection Java Interface
QueueConnection
createQueueSession()createConnectionConsumer()
(from jms)
<<Interface>>TopicConnection
createTopicSession()createConnectionConsumer()createDurableConnectionConsumer()
(from jms)
<<Interface>>
Connection
getClientID()setClientID()getMetaData()getExceptionListener()setExceptionListener()start()stop()close()
(from jms)
<<Interface>>
This picture shows Connection Java interface.
12/15/2004
69
Session Java Interface
? Created from a Connection object? Once connected to the provider via a
Connection, all work occurs in the context of a Session
? A session is single threaded, which means that any message sending and receiving happens in a serial order, one after the other
? Sessions also provide a transactional context
Session Java interface is created from Connection object. The communication between JMS client and JMS provider occurs through a Session. That is, JMS client has to create a Session before it wants to send or receive messages.
A Session is a single thread which means messages that are being sent and received in serial order under a single Session. Session also provides a transactional context.
12/15/2004
70
Session Java Interface
Session
$ AUTO_ACKNOWLEDGE : int = 1$ CLIENT_ACKNOWLEDGE : int = 2$ DUPS_OK_ACKNOWLEDGE : int = 3
createBytesMessage()createMapMessage()createMessage()createObjectMessage()createObjectMessage()createStreamMessage()createTextMessage()createTextMessage()getTransacted()commit()rollback()close()recover()getMessageListener()setMessageListener()run()
(from jms)
<<Interface>>
QueueSession
createQueue()createReceiver()createReceiver()createSender()createBrowser()createBrowser()createTemporaryQueue()
(from jms)
<<Interface>>TopicSession
createTopic()createSubscriber()createSubscriber()createDurableSubscriber()createDurableSubscriber()createPublisher()createTemporaryTopic()unsubscribe()
(from jms)
<<Interface>>
This picture shows Session Java interface.
12/15/2004
71
MessageProducer Java Interface
? To send a message to a Destination, a client must ask the Session object to create a MessageProducer object
Now MesageProducer interface. In order to send a message to a Destination, a JMS client has to create MessageProducer object (actually TopicPublisher and QueueSender object) from a Session object.
12/15/2004
72
MessageProducer Java Interface
QueueSender
getQueue()send()send()send()send()
(from jms)
<<Interface>>
MessageProducer
setDisableMessageID()getDisableMessageID()setDisableMessageTimestamp()getDisableMessageTimestamp()setDeliveryMode()getDeliveryMode()setPriority()getPriority()setTimeToLive()getTimeToLive()close()
(from jms)
<<Interface>>
TopicPublisher
getTopic()publish()publish()publish()publish()
(from jms)
<<Interface>>
This picture shows MessageProducer and its child interfaces (QueueSender and TopicPublisher).
12/15/2004
73
MessageConsumer Java Interface
? Clients which want to receive messages create MessageConsumer object via Session object
? MessageConsumer object is attached to a Destination object
? Client can receive messages in two different modes
– Blocking– Non-blocking
MessageConsumer Java interface is for the receiving side of JMS client. That is, JMS clients which want to receive messages have to create MessageConsumer object (actually QueueReceiver or TopicSubscriber object extends MesasgeConsumer) from Session object.
MessageConsumer object is attached to a Destination object. JMS client can receive messages in two different modes: blocking and non-blocking. Now let's talk about each of these two modes in a bit more detail.
12/15/2004
74
Receiving Messages in Blocking mode ? Client calls receive() method of
MessageConsumer object? Client blocks until a message is available
JMS clients which wants to receive messages in a blocking mode just calls receive() method of MessageConsumer object. In this mode, the client blocks until a message is available.
12/15/2004
75
Receiving Messages in Non-blocking mode ? Client registers a MessageListener object? Client does not block? When a message is available, JMS provider
then calls onMessage() method of the MessageListener object
A JMS client that receives messages in non-blocking mode has to register MessageListener object to a MessageConsumer object. In this mode, client does not block instead will get an notification through onMessage() metjod of the MessageListener object.
12/15/2004
76
MessageConsumer Java Interface
TopicSubscriber
getTopic()getNoLocal()
(from jms)
<<Interface>>QueueReceiver
getQueue()
(from jms)
<<Interface>>
MessageConsumer
getMessageSelector()getMessageListener()setMessageListener()receive()receive()receiveNoWait()close()
(from jms)
<<Interface>>
This picture shows the MessageConsumer and its child interfaces, QueueReceiver and TopicSubscriber.
12/15/2004
79
79
Steps for Writing JMS Sender Application
Now let's talk about how to write JMS client that sends messages.
12/15/2004
80
Steps for Building a JMS Sender Application
1.Get ConnectionFactory and Destination object (Topic or Queue) through JNDI
2.Create a Connection
3.Create a Session to send/receive messages
4.Create a MessageProducer (TopicPublisher or QueueSender)
5.Start Connection
6.Send (publish) messages
7.Close Session and Connection
The sequence of building JMS application is relatively straight-forward. First, get ConnectionFactory and Destination object through JNDI. Then create a connection to the messaging system. Then, create one or more sessions to send and receive messages. After creating sessions, you can create message producers (and message consumer if this JMS client plays role of message receiver as well). Then start Connection. Then Lastly, send messages and then at the end close Session and Connection.
Let’s take a look each of these steps in detail.
12/15/2004
81
(1) Locate ConnectionFactory and Destination objects via JNDI
// Get JNDI InitialContext objectContext jndiContext = new InitialContext();
// Locate ConnectionFactory object via JNDI TopicConnectionFactory factory = (TopicConnectionFactory) jndiContext.lookup( "MyTopicConnectionFactory");
// Locate Destination object (Topic or Queue) // through JNDITopic weatherTopic = (Topic) jndiContext.lookup("WeatherData");
There are two types of ConnectionFactory objects, one for point-to-point messaging model and the other for Publish and subscribe model. The one for pont-to-point model is called QueueConnectionFactory. And the one for publish-and-subscribe model is called TopicConnectionFactory.
This example code shows how to locate a TopicConnectionFactory and Destination object through JNDI. First you get the JNDI initial conext and using that initial context, searches for the the TopicConnectionFactory and Destination object whose symbolic name happened to be MyTopicConnectionFactory and WeatherData respectively.
Note that it is assumed that system administrator already have registered this particular instance of TopicConnectionFactory object with a symbolic name “MyTopicConnectionFactory” and a particular instance of Destination object with a symbolic name of “WeatherData”..
12/15/2004
82
(2) Create Connection Object
// Create a Connection object from // ConnectionFactory objectTopicConnection topicConnection = factory.createTopicConnection();
From ConnectionFactory object, you then create Connection object.
12/15/2004
83
3) Create a Session
// Create a Session from Connection object.// 1st parameter controls transaction// 2nd parameter specifies acknowledgment typeTopicSession session = topicConnection.createTopicSession (false, Session.CLIENT_ACKNOWLEDGE);
Once you create a Connection object through ConnectionFactory, you can now create a session. A session is a single threaded context for sending and receiving messages. That is, under a single session, the messages are sent or received in a serial fashion. Again, there are QueueSession and TopicSession for point-to-point and publish-and-subscribe models respectively.
Here you create TopicSession for publish-and-subscribe messaging model. The first parameter of the createTopicSession method is a boolean that indicates whether the returned session will use transaction or not. The second parameter is to specify message acknowledge mode. We will talk about these two parameters in a bit more detail later on.
12/15/2004
84
4) Create Message Producer
// Create MessageProducer from Session object// TopicPublisher for Pub/Sub// QueueSender for Point-to-PointTopicPublisher publisher = session.createPublisher(weatherTopic);
A session can create and service multiple Message producers and Message consumers. And in order to send or receive messages, you have to create Message producers and Message consumers. For the publish-and-subscribe model, it will create TopicPublisher object. Note that weatherTopic is the destination object that was located already through JNDI.
12/15/2004
85
(6) Start Connection
// Until Connection gets started, message flow// is inhibited: Connection must be started before// messages will be transmitted.topicConnection.start();
You then start a Connection. Until Connection is started, message flow does not occur meaning you have to start the Connection before messages can be transmitted or received.
12/15/2004
86
(6) Publish a Message
// Create a MessageTextMessage message =
session.createMessage();message.setText("text:35 degrees");
// Publish the messagepublisher.publish(message);
Finally you create a message body. In this example, it creates a textMessage which contains the text string “text: 35 degrees”, and then publish to a topic object, publisher.
12/15/2004
87
87
Steps for Writing Non-blocking mode JMS
Receiver Application
Now let's take a look at the steps on the receiver side. A typical JMS client sends and receives messages.
12/15/2004
88
Steps for Building a JMS Receiver Application (non-blocking mode)
1.Get ConnectionFactory and Destination object (Topic or Queue) through JNDI
2.Create a Connection 3.Create a Session to send/receive messages4.Create a MessageConsumer (TopicSubscriber or
QueueReceiver)5.Register MessageListener for non-blocking mode6.Start Connection7.Close Session and Connection
Since non-block mode and blocking mode works in a bit differently, let's talk about them separately.
The steps of receiving messages are not that much different except the steps in the red color. In the receiver side, JMS client has to create MessageConsumer object (actually TopicSubscriber or QueueReceiver).
In non-blocking mode, JMS client registers MessageListener object.
12/15/2004
89
4) Create Message Subscriber
// Create Subscriber from Session objectTopicSubscriber subscriber = session.createSubscriber(weatherTopic);
For the publish-and-subscribe model, it will create TopicPublisher object. Note that weatherTopic is the destination object that was located already through JNDI.
12/15/2004
90
5) Register MessageListener object for non-blocking mode// Create MessageListener objectWeatherListener myListener = new WeatherListener();
// Register MessageListener with // TopicSubscriber objectsubscriber.setMessageListener(myListener);
This example code the steps of creating MessageListener object and registers it with TopicSubscriber object.
12/15/2004
91
91
Steps for Writing blocking mode JMS
Receiver Application
Now let's talk about steps for writing blocking mode JMS client receiver.
12/15/2004
92
Steps for Building a JMS Receiver Application (non-blocking mode)1.Get ConnectionFactory and Destination
object (Topic or Queue) through JNDI2.Create a Connection 3.Create a Session to send/receive messages4.Create a MessageConsumer5.Start Connection6.Receive message7.Close Session and Connection
In blocking mode, you don't have to register your MessageListener object. Instead the client calls receive() method and blocks.
12/15/2004
93
93
How to Build RobustJMS Applications
This section explains how to use features of the JMS API to achieve the level of reliability and performance your application requires. Many people choose to implement JMS applications because they cannot tolerate dropped or duplicate messages and require that every message be received once and only once. The JMS API provides this functionality.
12/15/2004
94
Most Reliable Way
? The most reliable way to produce a message is to send a PERSISTENT message within a transaction.
? The most reliable way to consume a message is to do so within a transaction, either from a queue or from a durable subscription to a topic.
A
12/15/2004
95
Basic Reliability Mechanisms
? Controlling message acknowledgment? Specifying message persistence? Setting message priority levels? Allowing messages to expire? Creating temporary destinations
The basic mechanisms for achieving or affecting reliable message delivery are as follows:
* Controlling message acknowledgment: You can specify various levels of control over message acknowledgment. * Specifying message persistence: You can specify that messages are persistent, meaning that they must not be lost in the event of a provider failure. * Setting message priority levels: You can set various priority levels for messages, which can affect the order in which the messages are delivered. * Allowing messages to expire: You can specify an expiration time for messages so that they will not be delivered if they are obsolete. * Creating temporary destinations: You can create temporary destinations that last only for the duration of the connection in which they are created.
12/15/2004
96
Advanced JMS Reliability Mechanisms
? Creating durable subscriptions? Using local transactions
The more advanced mechanisms for achieving reliable message delivery are the following:
* Creating durable subscriptions: You can create durable topic subscriptions, which receive messages published while the subscriber is not active. Durable subscriptions offer the reliability of queues to the publish/subscribe message domain. * Using local transactions: You can use local transactions, which allow you to group a series of sends and receives into an atomic unit of work. Transactions are rolled back if they fail at any time.
12/15/2004
98
Phases of Message Consumption
? The client receives the message? The client processes the message? The message is acknowledged
– Acknowledgment is initiated either by the JMS provider or by the client, depending on the session acknowledgment mode
Until a JMS message has been acknowledged, it is not considered to be successfully consumed. The successful consumption of a message ordinarily takes place in three stages.
1. The client receives the message. 2. The client processes the message. 3. The message is acknowledged. Acknowledgment is initiated either by the JMS provider or by the client, depending on the session acknowledgment mode.
12/15/2004
99
Transaction And Acknowlegment
? In transacted sessions– Acknowledgment happens automatically when
a transaction is committed
– If a transaction is rolled back, all consumed messages are redelivered
? In nontransacted sessions– When and how a message is acknowledged
depend on the value specified (see next slide) as the second argument of the createSession method
In transacted sessions (see Using JMS API Local Transactions), acknowledgment happens automatically when a transaction is committed. If a transaction is rolled back, all consumed messages are redelivered.
In nontransacted sessions, when and how a message is acknowledged depend on the value specified as the second argument of the createSession method.
12/15/2004
100
Acknowledgment Types ? Auto acknowledgment (AUTO_ACKNOWLEDGE)
– Message is considered acknowledged when successful return on MessageConsumer.receive() or MessageListener.onMessage()
? Client acknowledgment (CLIENT_ACKKNOWLEDGE)– Client must call acknowledge() method of Message object
? Lazy acknowledgment (DUPS_OK_ACKNOWLEDGE)– Messaging system acknowledges messages as soon as they
are available for consumers
# Session.AUTO_ACKNOWLEDGE: The session automatically acknowledges a client's receipt of a message either when the client has successfully returned from a call to receive or when the MessageListener it has called to process the message returns successfully. A synchronous receive in an AUTO_ACKNOWLEDGE session is the one exception to the rule that message consumption is a three-stage process as described earlier.In this case, the receipt and acknowledgment take place in one step, followed by the processing of the message.
# Session.CLIENT_ACKNOWLEDGE: A client acknowledges a message by calling the message's acknowledge method. In this mode, acknowledgment takes place on the session level: Acknowledging a consumed message automatically acknowledges the receipt of all messages that have been consumed by its session. For example, if a message consumer consumes ten messages and then acknowledges the fifth message delivered, all ten messages are acknowledged.
# Session.DUPS_OK_ACKNOWLEDGE: This option instructs the session to lazily acknowledge the delivery of messages. This is likely to result in the delivery of some duplicate messages if the JMS provider fails, so it should be used only by consumers that can tolerate duplicate messages. (If the JMS provider redelivers a message, it must set the value of the JMSRedelivered message header to true.) This option can reduce session overhead by minimizing the work the session does to prevent duplicates.
12/15/2004
101
How Acknowledgment Type is set in JMS? An acknowledge type is set when Session is
created by setting appropriate flag– QueueConnection.createQueueSession(..,<flag>)– TopicConnection.createTopicSession(.., <flag>)
? Example TopicSession session =
topicConnection.createTopicSession (false, Session.CLIENT_ACKNOWLEDGE);
Acknowledgment type is set when Session object is created. In the example shown in the slide, the session is set with CLIENT_ACKNOWLEDGE type.
12/15/2004
103
Two Delivery Modes
? PERSISTENT delivery mode– Default– Instructs the JMS provider to take extra
care to ensure that a message is not lost in transit in case of a JMS provider failure
? NON_PERSISTENT delivery model– Does not require the JMS provider to store
the message– Better performance
The JMS API supports two delivery modes for messages to specify whether messages are lost if the JMS provider fails. These delivery modes are fields of the DeliveryMode interface.
* The PERSISTENT delivery mode, which is the default, instructs the JMS provider to take extra care to ensure that a message is not lost in transit in case of a JMS provider failure. A message sent with this delivery mode is logged to stable storage when it is sent. * The NON_PERSISTENT delivery mode does not require the JMS provider to store the message or otherwise guarantee that it is not lost if the provider fails.
12/15/2004
104
How to Specify Delivery Mode
? SetDeliveryMode method of the MessageProducer interface
– producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
? Use the long form of the send or the publish method
– producer.send(message, DeliveryMode.NON_PERSISTENT, 3,10000);
You can specify the delivery mode in either of two ways.
* You can use the setDeliveryMode method of the MessageProducer interface to set the delivery mode for all messages sent by that producer. For example, the following call sets the delivery mode to NON_PERSISTENT for a producer: producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); * You can use the long form of the send or the publish method to set the delivery mode for a specific message. The second argument sets the delivery mode. For example, the following send call sets the delivery mode for message to NON_PERSISTENT: producer.send(message, DeliveryMode.NON_PERSISTENT, 3, 10000); The third and fourth arguments set the priority level and expiration time, which are described in the next two subsections.
If you do not specify a delivery mode, the default is PERSISTENT. Using the NON_PERSISTENT delivery mode may improve performance and reduce storage overhead, but you should use it only if your application can afford to miss messages.
12/15/2004
106
How to Set Delivery Priority
? Ten levels of priority range – from 0 (lowest) to 9 (highest)
– Default is 4? Use the setPriority method of the
MessageProducer interface – producer.setPriority(7);
? Use the long form of the send or the publish method
– producer.send(message, DeliveryMode.NON_PERSISTENT, 7, 10000);
You can use message priority levels to instruct the JMS provider to deliver urgent messages first. You can set the priority level in either of two ways.
* You can use the setPriority method of the MessageProducer interface to set the priority level for all messages sent by that producer. For example, the following call sets a priority level of 7 for a producer:
producer.setPriority(7); * You can use the long form of the send or the publish method to set the priority level for a specific message. The third argument sets the priority level. For example, the following send call sets the priority level for message to 3:
producer.send(message, DeliveryMode.NON_PERSISTENT, 3, 10000);
The ten levels of priority range from 0 (lowest) to 9 (highest). If you do not specify a priority level, the default level is 4. A JMS provider tries to deliver higher-priority messages before lower-priority ones but does not have to deliver messages in exact order of priority.
12/15/2004
108
How to set Message Expiration
? Use the setTimeToLive method of the MessageProducer interface
– producer.setTimeToLive(60000);? Use the long form of the send or the publish
method – producer.send(message,
DeliveryMode.NON_PERSISTENT, 3, 60000);
A
12/15/2004
110
Maximum Reliability
? To ensure that a pub/sub application receives all published messages
– Use PERSISTENT delivery mode for the publishers
– In addition, use durable subscriptions for the subscribers
? Use the Session.createDurableSubscriber method to create a durable subscriber
To ensure that a pub/sub application receives all published messages, use PERSISTENT delivery mode for the publishers. In addition, use durable subscriptions for the subscribers.The Session.createConsumer method creates a nondurable subscriber if a topic is specified as the destination. A nondurable subscriber can receive only messages that are published while it is active.
12/15/2004
111
How Durable Subscription Works
? A durable subscription can have only one active subscriber at a time
? A durable subscriber registers a durable subscription by specifying a unique identity that is retained by the JMS provider
? Subsequent subscriber objects that have the same identity resume the subscription in the state in which it was left by the preceding subscriber
? If a durable subscription has no active subscriber, the JMS provider retains the subscription's messages until they are received by the subscription or until they expire
A
12/15/2004
113
Transactions in JMS
? Transaction scope is only between client and Messaging system not between clients
– a group of messages are dispatched as a unit (on the sender side)
– a group of messages are retrieved as a unit (on the receiver side)
? “Local” and “Distributed” transactions
As was mentioned before, JMS supports transactional scope only between client and messaging system and not between clients.
Now there are local and distributed transactions and we will talk about them in the following slides.
12/15/2004
114
Local Transactions in JMS
? Local transactions are controlled by Session object
? Transaction begins when a session is created– There is no explicit “begin transaction” method
? Transaction ends when Session.commit() or Session.abort() is called
? Transactional session is created by specifying appropriate flag when a session is created
– QueueConnection.createQueueSession(true, ..)– TopicConnection.createTopicSession(true, ..)
H
12/15/2004
115
Distributed Transactions in JMS
? Coordinated by a transactional manager? Applications will control the transaction via
JTA methods– Use of Session.commit() and Session.rollback() is
forbidden
? Messaging operations can be combined with database transactions in a single transaction
H
12/15/2004
117
JMS Message Selector
? (Receiver) JMS application uses a selector to select only the messages that are of interest
? A selector is essentially a SQL92 string that specifies “selection” (or filtering) rule
– A Teller object listening for Account objects as messages may be required to do something only when the account balance drops below a $1000
Receiving JMS client application can specify message selector to selectively receive messages. A message selector is essentially a SQL92 string that specifies the selection rules.
12/15/2004
118
Example: JMS Message Selectors
? The selector cannot reference the contents of a message
? It can access the properties and header? Examples
– JMSType==’wasp’– phone LIKE ‘223’– price BETWEEN 100 AND 200– name IN(‘sameer’,’tyagi’)– JMSType IS NOT NULL
The selector cannot reference the contents of a message. However, it can access the properties and header.
12/15/2004
120
Messaging Features Not Defined in JMS (No APIs)
? Encryption– JMS spec assumes messaging system handles it
? Access control– JMS spec assumes messaging system handles it
? Load balancing? Administration of queues and topics
JMS in its current form depend on the messaging systems as far as security features such as encryption and access control are concerned. Load balancing and adminstration of the queues and topics are also considered to be messaging system specific features.
12/15/2004
122
JMS and MDB
JMS ProviderEJB Container
Destin-ation
Consumer
Instances
Msg-drivenBean Class
This picture shows how JMS and Message-Driven Beans are working together. MDB is instantiated when a message is received asynchronously.
12/15/2004
123
MDB Example
OrderBean
InventoryManagement
Bean
MessageDrivenBean
JMS Topics
Publish/subscribe
ProcessOrder
Procure Inventory
<Entity EJB>
<Entity EJB>
This is another example. Let's say that you are building purchase order handling applications. You first create JMS topics like “orderReceiver”. Whenever a new message indicating an order request, a MDB gets instantiated. Within the onMessage() method of the MDB, the actual purchase order handling business logic such as calling entity bean to process order or to handle inventory or sending an confirmation email to the customer gets executed.
12/15/2004