Tài liệu O''''Reilly - Java Message Service doc - Pdf 90


Java Message Service
Richard Monson-Haefel
David A. Chappell

Publisher: O'Reilly

First Edition January 2001

ISBN: 0-596-00068-5, 238 pages

This book is a thorough introduction to Java Message Service (JMS) from Sun
Microsystems. It shows how to build applications using the point-to-point and publish-and-
subscribe models; use features like transactions and durable subscriptions to make
applications reliable; and use messaging within Enterprise JavaBeans. It also introduces a
new EJB type, the MessageDrivenBean, that is part of EJB 2.0, and discusses integration
of messaging into J2EE.
Team[oR]
Table of Contents
Preface ..............................................................................................................................1
What Is the Java Message Service?.................................................................................1
Who Should Read This Book?........................................................................................1

Chapter 5. Point-to-Point Messaging.............................................................................69
5.1 Point-to-Point and Publish-and-Subscribe...............................................................69
5.2 The QWholesaler and QRetailer..............................................................................71
5.3 Creating a Queue Dynamically ...............................................................................78
5.4 Load Balancing Using Multiple QueueSessions......................................................79
5.5 Examining a Queue.................................................................................................80

Chapter 6. Guaranteed Messaging, Transactions, Acknowledgments & Failures ......84
6.1 Guaranteed Messaging............................................................................................84
6.2 Message Acknowledgments....................................................................................85
6.3 Message Groups and Acknowledgment...................................................................91
6.4 Transacted Messages ..............................................................................................95
6.5 Lost Connections ..................................................................................................104
6.6 Dead Message Queues ..........................................................................................106

Chapter 7. Deployment Considerations.......................................................................108
7.1 Performance, Scalability, and Reliability ..............................................................108
7.2 To Multicast or Not to Multicast ...........................................................................112
7.3 Security................................................................................................................116
7.4 Connecting to the Outside World ..........................................................................118
7.5 Bridging to Other Messaging Systems ..................................................................120

Chapter 8. J2EE, EJB, and JMS..................................................................................122
8.1 J2EE Overview.....................................................................................................122
8.2 J2EE: A United Platform ......................................................................................125
8.3 The JMS Resource in J2EE...................................................................................126
8.4 The New Message-Driven Bean in EJB 2.0...........................................................128

D.4 Arithmetic Operators............................................................................................177
D.5 Declaring a Message Selector ..............................................................................178
D.6 Not Delivered Semantics......................................................................................179

Colophon.......................................................................................................................180

Java Message Service

1
Preface
What Is the Java Message Service?
When Java™ was first introduced, most of the IT industry focused on its graphical user
interface characteristics and the competitive advantage it offered in terms of distribution
and platform independence. Today, the focus has broadened considerably: Java has been
recognized as an excellent platform for creating enterprise solutions, specifically for
developing distributed server-side applications. This shift has much to do with Java's
emerging role as a universal language for producing implementation-independent
abstractions for common enterprise technologies. The JDBC™ API is the first and most
familiar example. JDBC provides a vendor-independent Java interface for accessing SQL
relational databases. This abstraction has been so successful that it's difficult to find a
relational database vendor that doesn't support JDBC. Java abstractions for enterprise
technologies have expanded considerably to include JNDI (Java Naming and Directory
Interface™) for abstracting directory services, JMX (Java Management Extensions) for
abstracting access to computer devices on a network, and JMS™ (Java Message Service)
for abstracting access to different Message-Oriented Middleware products.
JMS has quickly become a de facto industry standard. In its second version, most
enterprise messaging vendors now support the JMS specification, making for a large
selection of JMS providers to choose from.
The Java Message Service is a Java API implemented by enterprise messaging vendors to
provide Java applications with a common and elegant programming model that is portable

background in distributed computing, we recommend Java™ Distributed Computing by
Jim Farley (O'Reilly).
Organization
Here's how the book is structured. The first chapter explains messaging systems,
centralized and distributed architectures, and how and why JMS is important. Chapter 2
through Chapter 5 go into detail about developing JMS clients using the two messaging
models, publish-and-subscribe and point-to-point. Chapter 6 and Chapter 7 should be
considered "advanced topics," covering deployment and administration of messaging
systems. Chapter 8 is an overview of the Java™ 2, Enterprise Edition (J2EE) with regard
to JMS, including coverage of the new message-driven bean in Enterprise JavaBeans 2.0.
Finally, Chapter 9 provides a summary of several JMS vendors and their products.
Chapter 1
Defines enterprise messaging and common architectures used by messaging vendors.
JMS is defined and explained, as are its two programming models, publish-and-
subscribe and point-to-point.
Chapter 2
Walks the reader through the development of a simple publish-and-subscribe JMS
client.
Chapter 3
Provides a detailed examination of the JMS message, the most important part of the
JMS API.
Chapter 4
Examines the publish-and-subscribe programming model through the development
of a B2B JMS application.
Chapter 5
Examines the point-to-point programming models through the enhancement of the
B2B JMS application developed in Chapter 4.
Java Message Service

3

Java Message Service

4
Examples developed in this book are available through the book's catalog page at
http://www.oreilly.com/catalog/javmesser/examples. The examples are organized by
chapter. Special source code modified for specific vendors is also provided. These vendor-
specific examples include a readme.txt file that points to documentation for downloading
and installing the JMS provider, as well as specific instructions on setting up the provider
for each example.
Conventions
Italic is used for filenames, pathnames, hostnames, domain names, URLs, email addresses,
and new terms where they are defined.
Constant width is used for code examples and fragments, class, variable, and method
names, Java keywords used within the text, SQL commands, table names, column names,
and XML elements and tags.
Constant width bold is used for emphasis in some code examples.
Constant width italic is used to indicate text that is replaceable.
The term "JMS provider" is used to refer to a vendor that implements the JMS API to
provide connectivity to their enterprise messaging service. The term "JMS client" refers to
Java components or applications that use the JMS API and a JMS provider to send and
receive messages. "JMS application" refers to any combination of JMS clients that work
together to provide a software solution.
Comments and Questions
We have tested and verified the information in this book to the best of our ability, but you
may find that features have changed (or even that we have made mistakes!). Please let us
know about any errors you find, as well as your suggestions for future editions, by writing
to:
O'Reilly & Associates, Inc.
101 Morris Street
Sebastopol, CA 95472

critical to the technical and conceptual accuracy of this book. They brought a combination
of industry and real-world experience to bear, and helped to make this the best book on
JMS published today.
Thanks also to Mark Hapner of Sun Microsystems, the primary architect of Java 2,
Enterprise Edition, who answered several of our most complex questions. Thanks to all the
participants in the JMS-INTEREST mailing list hosted by Sun Microsystems for their
interesting and informative postings.

Java Message Service

6
Chapter 1. Understanding the Messaging Paradigm
Computers and people can communicate by using messaging systems to exchange
messages over electronic networks. The most ubiquitous messaging system today is email,
which facilitates communication among people. While email is an important human-to-
human messaging system, this book is not about email. Instead, this book is concerned
with messaging systems that allow different software applications to communicate with
each other. These application-to-application messaging systems, when used in business
systems, are generically referred to as enterprise messaging systems, or Message-Oriented
Middleware (MOM).
Enterprise messaging systems allow two or more applications to exchange information in
the form of messages. A message, in this case, is a self-contained package of business data
and network routing headers. The business data contained in a message can be anything -
depending on the business scenario - and usually contains information about some
business transaction. In enterprise messaging systems, messages inform an application of
some event or occurrence in another system.
Using Message-Oriented Middleware, messages are transmitted from one application to
another across a network. MOM products ensure that messages are properly distributed
among applications. In addition, MOMs usually provide fault tolerance, load balancing,
scalability, and transactional support for enterprises that need to reliably exchange large

language - other than that, everything is explained.
1.1 Enterprise Messaging
Enterprise messaging is not a new concept. Messaging products such as IBM MQSeries,
Microsoft MSMQ, TIBCO Rendevous, Open Horizon Ambrosia, and Modulus InterAgent
have been in existence for many years. Newer messaging products such as Progress
SonicMQ, Softwired iBus, and FioranoMQ have been built from the ground up, based on
the need for doing reliable Business-to-Business communications over the Internet.
A key concept of enterprise messaging is messages are delivered asynchronously from one
system to others over a network. To deliver a message asynchronously means the sender is
not required to wait for the message to be received or handled by the recipient; it is free to
send the message and continue processing. Asynchronous messages are treated as
autonomous units - each message is self-contained and carries all of the data and state
needed by the business logic that processes it.
In asynchronous messaging, applications use a simple API to construct a message, then
hand it off to the Message-Oriented Middleware for delivery to one or more intended
recipients (Figure 1.1). A message is a package of business data that is sent from one
application to another over the network. The message should be self-describing in that it
should contain all the necessary context to allow the recipients to carry out their work
independently.
Figure 1.1. Message-Oriented Middleware

Message-Oriented Middleware architectures of today vary in their implementation. The
spectrum ranges from a centralized architecture that depends on a message server to
perform routing, to a decentralized architecture that distributes the "server" processing out
to the client machines. A varied array of protocols including TCP/IP, HTTP, SSL, and IP
multicast are employed at the network transport layer. Some messaging products use a
hybrid of both approaches, depending on the usage model.
Java Message Service

8

group. In this way, applications can send messages to an IP multicast address and expect
the network layer to redistribute the messages appropriately (see Figure 1.3). Unlike a
centralized architecture, a distributed architecture doesn't require a server for the purposes
of routing messages - the network handles routing automatically. However, other server-
like functionality is still required to be included with each client, such as message
persistence and message delivery semantics like once-and-only-once delivery.
Figure 1.3. Decentralized IP multicast architecture

1.1.3 Hybrid Architectures
A decentralized architecture usually implies that an IP multicast protocol is being used. A
centralized architecture usually implies that the TCP/IP protocol is the basis for
communication between the various components. A messaging vendor's architecture may
also combine the two approaches. Clients may connect to a daemon process using TCP/IP,
which in turn communicate with other daemon processes using IP multicast groups.
1.1.4 Centralized Architecture as a Model
Both ends of the decentralized and centralized architecture spectrum have their place in
enterprise messaging. The advantages and disadvantages of distributed versus centralized
architectures are discussed in more detail in Chapter 7. In the meantime we need a
common model for discussing other aspects of enterprise messaging. In order to simplify
discussions, this book uses a centralized architecture as a logical view of enterprise
messaging. This is for convenience only and is not an endorsement of centralized over
decentralized architectures. The term "message server" is frequently used in this book to
refer to the underlying architecture that is responsible for routing and distributing
messages. In centralized architectures, the message server is a middleware server or cluster
of servers. In decentralized architectures, the server refers to the local server-like facilities
of the client.
1.2 The Java Message Service (JMS)
The Java Message Service (JMS) is an API for enterprise messaging created by Sun
Microsystems. JMS is not a messaging system itself; it's an abstraction of the interfaces
and classes needed by messaging clients when communicating with messaging systems. In

In the simplest sense, publish-and-subscribe is intended for a one-to-many broadcast of
messages, while point-to-point is intended for one-to-one delivery of messages (see Figure
1.4).
Figure 1.4. JMS messaging domains

Java Message Service

11
Messaging clients in JMS are called JMS clients, and the messaging system - the MOM - is
called the JMS provider. A JMS application is a business system composed of many JMS
clients and, generally, one JMS provider.
In addition, a JMS client that produces a message is called a producer, while a JMS client
that receives a message is called a consumer. A JMS client can be both a producer and a
consumer. When we use the term consumer or producer, we mean a JMS client that
consumes messages or produces messages, respectively. We use this terminology
throughout the book.
1.2.1.1 Publish-and-subscribe
In pub/sub, one producer can send a message to many consumers through a virtual channel
called a topic. Consumers, which receive messages, can choose to subscribe to a topic.
Any messages addressed to a topic are delivered to all the topic's consumers. Every
consumer receives a copy of each message. The pub/sub messaging model is by and large
a push-based model, where messages are automatically broadcast to consumers without
them having to request or poll the topic for new messages.
In the pub/sub messaging model the producer sending the message is not dependent on the
consumers receiving the message. Optionally, JMS clients that use pub/sub can establish
durable subscriptions that allow consumers to disconnect and later reconnect and collect
messages that were published while they were disconnected. The pub/sub JMS messaging
model is discussed in greater detail in Chapter 2, and Chapter 4.
1.2.1.2 Point-to-point
The point-to-point messaging model allows JMS clients to send and receive messages both

queues, which provide an abstraction that decouples participating applications.
As an example, a messaging system might be used to integrate an Internet order processing
system with an Enterprise Resource Planning (ERP) system like SAP. The Internet system
uses JMS to deliver business data about new orders to a topic. An ERP gateway
application, which accesses a SAP application via its native API, can subscribe to the order
topic. As new orders are broadcast to the topic, the gateway receives the orders and enters
them into the SAP application.
1.3.2 Business-to-Business
Historically, businesses exchanged data using Electronic Data Interchange (EDI) systems.
Data was exchanged using rigid, fixed formats over proprietary Value-Added Networks
(VANs). Cost of entry was high and data was usually exchanged in batch processes - not
as real-time business events.
The Internet, XML, and modern messaging systems have radically changed how
businesses exchange data and interact in what is now called Business-to-Business (B2B).
The use of messaging systems is central to modern B2B solutions because it allows
organizations to cooperate without requiring them to tightly integrate their business
systems. In addition, it lowers the barriers to entry since finer-grained participation is
possible. Businesses can join in B2B and disengage depending on the queues and topics
with which they interact.
A manufacturer, for example, can set up a topic for broadcasting requests for bids on raw
materials. Suppliers can subscribe to the topic and respond by producing messages back to
the manufacturer's queue. Suppliers can be added and removed at will, and new topics and
queues for different types of inventory and raw materials can be used to partition the
systems appropriately.
1.3.3 Geographic Dispersion
These days many companies are geographically dispersed. Brick-and-mortar, click-and-
mortar, and dot-coms all face problems associated with geographic dispersion of enterprise
systems. Inventory systems in remote warehouses need to communicate with centralized
back-office ERP systems at corporate headquarters. Sensitive employee data that is
administered locally at each subsidiary needs to be synchronized with the main office.

an as-needed basis. A common scenario might be if you discover a need to add an audit-
trail mechanism for certain messages and not others. Figure 1.5 shows you how to plug in
a specialized auditing and logging JMS client whose only job is to track specific messages,
just by subscribing to the topics you are interested in.
The ability to add and remove producers and consumers allows enterprise systems to
dynamically alter the routing and re-routing of messages in an already deployed
environment.
As another example, we can build on the EAI scenario discussed previously. In this
example, a gateway accepts incoming purchase orders, converts them to the format
appropriate for a legacy ERP system, and calls into the ERP system for processing (see
Figure 1.6). Java Message Service

14
Figure 1.5. Dynamically adding auditing and logging using publish-and-subscribe

Figure 1.6. Integration of purchase order system with an ERP system

In Figure 1.6, other JMS applications (A and B) also subscribe to the purchase order topic
and do their own independent processing. Application A might be a legacy application in
the company, while application B may be another company's business system, representing
a B2B integration.
Using JMS, it's fairly easy to add and remove applications from this process. For example,
if purchase orders need to be processed from two different sources, such as an Internet-
based system and a legacy EDI system, you can simply add the legacy purchase order
system to the mix (see Figure 1.7).
Java Message Service


most modern examples of this architecture.
Java Message Service

16
With J2EE, JSP and Servlets represent the presentation tier while Enterprise JavaBeans is
the middle tier. Microsoft's DNA is architecturally similar to J2EE, relying on ASP for
presentation and COM+ for the middle tier. Regardless of the platform, the core
technology used in these systems is RPC-based middleware. Whether it's the EJB or
COM+, RPC is the defining communication paradigm.
RPC attempts to mimic the behavior of a system that runs in one process. When a remote
procedure is invoked, the caller is blocked until the procedure completes and returns
control to the caller. This synchronized model allows the developer to view the system as
if it runs in one process. Work is performed sequentially, ensuring that tasks are completed
in a predefined order. The synchronized nature of RPC tightly couples the client (the
software making the call) to the server (the software servicing the call). The client cannot
proceed - it is blocked - until the server responds.
The tightly coupled nature of RPC creates highly interdependent systems where a failure
on one system has an immediate and debilitating impact on other systems. In J2EE, for
example, the EJB server must be functioning properly if the servlets that use enterprise
beans are expected to function.
RPC works well in many scenarios, but its synchronous, tightly coupled nature is a severe
handicap in system-to-system processing where vertical applications are integrated
together. In system-to-system scenarios, the lines of communication between vertical
systems are many and multidirectional, as Figure 1.8 illustrates.
Figure 1.8. Tightly coupled with synchronous RPC

Consider the challenge of implementing this infrastructure using a tightly coupled RPC
mechanism. There is the many-to-many problem of managing the connections between
these systems. When you add another application to the mix, you have to go back and let
all the other systems know about it. Also, systems can crash. Scheduled downtimes need to

messaging server, so that a failure in one does not impede the operation of the others.
Figure 1.9. JMS provides a loosely coupled environment where partial failure of system
components does not impede overall system availability

Partial failure in a networked system is a fact of life. One of the systems may have an
unpredictable failure or need to be shut down at some time during its continuous operation.
This can be further magnified by geographic dispersion of in-house and partner systems. In
Java Message Service

18
recognition of this, JMS provides guaranteed delivery, which ensures that intended
consumers will eventually receive a message even if partial failure occurs.
Guaranteed delivery uses a store-and-forward mechanism, which means that the
underlying message server will write the incoming messages out to a persistent store if the
intended consumers are not currently available. When the receiving applications become
available at a later time, the store-and-forward mechanism will deliver all of the messages
that the consumers missed while unavailable (see Figure 1.10).
Figure 1.10. Underlying store-and-forward mechanism guarantees delivery of messages

To summarize, JMS is not just another event service. It was designed to cover a broad
range of enterprise applications, including EAI, B2B, push models, etc. Through
asynchronous processing, store-and-forward, and guaranteed delivery, it provides high
availability capabilities to keep business applications in continuous operation with
uninterrupted service. It offers flexibility of integration by providing publish-and-subscribe
and point-to-point functionality. Through location transparency and administrative control,
it allows for a robust, service-based architecture. And most importantly, it is extremely
easy to learn and use. In the next chapter we will take a look at how simple it is by
building our first JMS application.
Java Message Service


import java.io.InputStreamReader;
import java.util.Properties;

public class Chat implements javax.jms.MessageListener{
private TopicSession pubSession;
private TopicSession subSession;
private TopicPublisher publisher;
private TopicConnection connection;
private String username;

/* Constructor. Establish JMS publisher and subscriber */
public Chat(String topicName, String username, String password)
throws Exception {
// Obtain a JNDI connection
Properties env = new Properties( );
// ... specify the JNDI properties specific to the vendor

InitialContext jndi = new InitialContext(env);

// Look up a JMS connection factory
Java Message Service

20
TopicConnectionFactory conFactory =
(TopicConnectionFactory)jndi.lookup("TopicConnectionFactory");

// Create a JMS connection
TopicConnection connection =
conFactory.createTopicConnection(username,password);


String username) {
this.connection = con;
this.pubSession = pubSess;
this.subSession = subSess;
this.publisher = pub;
this.username = username;
}
/* Receive message from topic subscriber */
public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText( );
System.out.println(text);
} catch (JMSException jmse){ jmse.printStackTrace( ); }
}
/* Create and send message using topic publisher */
protected void writeMessage(String text) throws JMSException {
TextMessage message = pubSession.createTextMessage( );
message.setText(username+" : "+text);
publisher.publish(message);
}
/* Close the JMS connection */
public void close( ) throws JMSException {
connection.close( );
}
/* Run the Chat client */
public static void main(String [] args){
try{
if (args.length!=3)
System.out.println("Topic or username missing");

The topic is the destination that we want to publish-and-subscribe to; username and
password make up the authentication information for the client. Run at least two chat
clients in separate command windows and try typing into one; you should see the text you
type displayed by the other client.
Figure 2.1. The Chat application


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status