Java Message Service (Mark Richards, Richard Monson-Haefel etc.) (Z-Library)
Author: Richard Monson-Haefel, David Chappell
科学
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-andsubscribe 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.
📄 File Format:
PDF
💾 File Size:
1.9 MB
14
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
SECOND EDITION Java Message Service Mark Richards, Richard Monson-Haefel, and David A. Chappell Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
📄 Page
2
Java Message Service, Second Edition by Mark Richards, Richard Monson-Haefel, and David A. Chappell Copyright © 2009 Mark Richards. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Mike Loukides and Julie Steele Production Editor: Sarah Schneider Production Services: Appingo, Inc. Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: May 2009: Second Edition. O’Reilly and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Java Message Service, Second Edition, the image of a passenger pigeon, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-0-596-52204-9 [C] 1242320347
📄 Page
3
Table of Contents Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Messaging Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 The Advantages of Messaging 3 Heterogeneous Integration 3 Reduce System Bottlenecks 3 Increase Scalability 4 Increase End User Productivity 4 Architecture Flexibility and Agility 5 Enterprise Messaging 5 Centralized Architectures 7 Decentralized Architectures 7 Hybrid Architectures 8 Centralized Architecture As a Model 8 Messaging Models 9 Point-to-Point 10 Publish-and-Subscribe 10 JMS API 11 Point-to-Point API 13 Publish-and-Subscribe API 14 Real-World Scenarios 14 Service-Oriented Architecture 15 Event-Driven Architecture 16 Heterogeneous Platform Integration 16 Enterprise Application Integration 17 Business-to-Business 17 Geographic Dispersion 18 Information Broadcasting 18 Building Dynamic Systems 18 RPC Versus Asynchronous Messaging 21 v
📄 Page
4
Tightly Coupled RPC 21 Enterprise Messaging 23 2. Developing a Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 The Chat Application 25 Getting Started with the Chat Example 28 Examining the Source Code 30 Sessions and Threading 39 3. Anatomy of a JMS Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Headers 42 Automatically Assigned Headers 43 Developer-Assigned Headers 46 Properties 47 Application-Specific Properties 47 JMS-Defined Properties 49 Provider-Specific Properties 50 Message Types 50 Message 50 TextMessage 51 ObjectMessage 52 BytesMessage 53 StreamMessage 56 MapMessage 58 Read-Only Messages 60 Client-Acknowledged Messages 61 Interoperability and Portability of Messages 61 4. Point-to-Point Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Point-to-Point Overview 63 When to Use Point-to-Point Messaging 66 The QBorrower and QLender Application 67 Configuring and Running the Application 67 The QBorrower Class 69 The QLender Class 76 Message Correlation 81 Dynamic Versus Administered Queues 83 Load Balancing Using Multiple Receivers 84 Examining a Queue 85 5. Publish-and-Subscribe Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Publish-and-Subscribe Overview 87 When to Use Publish-and-Subscribe Messaging 89 vi | Table of Contents
📄 Page
5
The TBorrower and TLender Application 90 Configuring and Running the Application 90 The TLender Class 92 The TBorrower Class 96 Durable Versus Nondurable Subscribers 100 Dynamic Versus Administered Subscribers 101 Unsubscribing Dynamic Durable Subscribers 104 Temporary Topics 104 6. Message Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Message Selectors 109 Identifiers 110 Literals 111 Comparison Operators 111 Arithmetic Operators 113 Declaring a Message Selector 114 Message Selector Examples 116 Managing Claims in an HMO 116 Notification of Certain Bids on Inventory 116 Priority Handling 116 Stock Trade Order Auditing 117 Not Delivered Semantics 117 Design Considerations 118 7. Guaranteed Messaging and Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Guaranteed Messaging 125 Message Autonomy 126 Store-and-Forward Messaging 126 Message Acknowledgments and Failure Conditions 126 Message Acknowledgments 127 AUTO_ACKNOWLEDGE 127 DUPS_OK_ACKNOWLEDGE 132 CLIENT_ACKNOWLEDGE 132 Message Groups and Acknowledgment 133 Handling Redelivery of Messages in an Application 134 Message Groups Example 134 Message Grouping and Multiple Receivers 143 Transacted Messages 145 Creating and Using a JMS Transaction 147 Transacted Session Example 147 Distributed Transactions 150 Lost Connections 151 The ExceptionListener Example 152 Table of Contents | vii
📄 Page
6
Dead Message Queues 153 8. Java EE and Message-Driven Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Java EE Overview 155 Enterprise JavaBeans 156 Enterprise JavaBeans 3.0 (EJB3) Overview 157 Simplified Bean Development 158 Dependency Injection 158 Simplified Callback Methods 159 Programmatic Defaults 159 Interceptors 160 Java Persistence API 162 JMS Resources in Java EE 162 The JNDI Environment Naming Context (ENC) 164 Message-Driven Beans 166 Concurrent Processing and Scalability 168 Defining Message-Driven Beans 168 Message-Driven Bean Use Cases 171 Message Facade 171 Transformation and Routing 173 9. Spring and JMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Spring Messaging Architecture 177 JmsTemplate Overview 180 Send Methods 181 convertAndSend Methods 181 receive and receiveSelected Methods 182 receiveAndConvert Methods 183 Connection Factories and JMS Destinations 184 Using JNDI 184 Using Native Classes 187 Sending Messages 189 Using the send Method 190 Using the convertAndSend Method 191 Using a Nondefault JMS Destination 193 Receiving Messages Synchronously 195 Message-Driven POJOs 198 The Spring Message Listener Container 198 MDP Option 1: Using the MessageListener Interface 199 MDP Option 2: Using the SessionAwareMessageListener Interface 201 MDP Option 3: Using the MessageListenerAdapter 202 Message Conversion Limitations 207 The Spring JMS Namespace 208 viii | Table of Contents
📄 Page
7
<jms:listener-container> Element Properties 209 <jms:listener> Element Properties 211 10. Deployment Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 Performance, Scalability, and Reliability 213 Determining Message Throughput Requirements 213 Testing the Real-World Scenario 214 To Multicast or Not to Multicast 217 TCP/IP 218 UDP 218 IP Multicast 218 Messaging Over IP Multicast 219 The Bottom Line 221 Security 222 Authentication 222 Authorization 223 Secure Communication 224 Firewalls and HTTP Tunneling 224 Connecting to the Outside World 225 Bridging to Other Messaging Systems 227 11. Messaging Design Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Internal Versus External Destination 229 Internal Destination Topology 230 External Destination Topology 231 Request/Reply Messaging Design 232 Messaging Design Anti-Patterns 236 Single-Purpose Queue 236 Message Priority Overuse 240 Message Header Misuse 240 A. The Java Message Service API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 B. Message Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 C. Message Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 D. Installing and Configuring ActiveMQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 Table of Contents | ix
📄 Page
8
Foreword For close to a decade now, I’ve been a fan of messaging-based systems. They offer a degree of reliability, flexibility, extensibility, and modularity that a traditional RPC or distributed object system simply cannot. Working with them takes a bit of adjustment, because they don’t quite behave the same way that an architect or designer expects a traditional n-tier system to behave. This is not to say that they’re better or worse; they’re just different. Instead of invoking methods on objects directly, where the object can hold conversational state or context, now the message itself has to be self-contained and state-complete. Which raises an important point. For any given developer with respect to any given technology, there are four distinct stages. The first is the Ignorant. We may know the technology exists, or not, but beyond that we remain entirely ignorant about its capabilities. It’s a collection of letters, at best, often mentioned in conjunction with other technologies that may or may not matter to what we’re doing on a daily basis. The second is the Explorer. Something piques our curiosity, voluntarily or not. We begin some initial forays into the jungle, perhaps downloading an implementation or reading a few articles. We begin to understand the basic framing of where this thing sits in the broad scheme of things and maybe how it’s supposed to work, but our hands- on experience is generally limited to the moral equivalent of “Hello World” and a few other samples. The third is the Journeyman. After running many of the samples and reading a few articles, we realize that we understand it at a basic level and begin to branch out to writing code with it. We feel reasonably comfortable introducing it into production code and reasonably comfortable debugging the stupid mistakes we’ll make with it. We’re not experts, by any means, but we can at least get the stuff to compile and run most of the time. The last, of course, is the Master. After building a few systems and seeing how they react under real-world conditions, we have a deep gestalt with it and can often predict how the tool or technology will react without even running the code. We can see how xi
📄 Page
9
this thing will interact with other, complementary technologies, and understand how to achieve some truly miraculous results, such as systems that resist network outages or machine failures. When the Java Message Service (JMS) API was first released, back in 1999, before any noncommercial/open-source implementations were available, I distinctly remember looking at it, thinking, “Well, it seems interesting, but it’s not something I can use without a real implementation,” and setting my printed copy of the specification off to one side for later perusal. My transition to Explorer and Journeyman came a few years later, as I came to understand the power of messaging systems, partly thanks to the few implementations out, partly thanks to my own ex- ploration of other messaging systems (most notably MSMQ and Tibco), but mostly due to the person who wrote this second edition of Java Message Service. I’m still well shy of Master status. Fortunately, both you and I know somebody who is not. Mark Richards has spent the last several years living the messaging lifestyle, both as an architect and implementor as well as a leader and luminary: the first in his capacity as a consultant, the second in his capacity as a speaker on the No Fluff Just Stuff (NFJS) tour. He has a great “take” on the reasons for and the implications of building message- based systems, and he brings that forth in this nearly complete rewrite of Richard Monson-Haefel and Dave Chappell’s first edition. Even if you’re in the Ignorant stage of JMS, Mark’s careful walkthrough of the basics, through implementation and then the design pros and cons of messaging will bring you to the Journeyman stage fast and leave you with the necessary structure in place to let you reach that Master stage in no time at all. And that, my friend, is the best anybody can ask of a book. Happy messaging. —Ted Neward Principal Consultant,ThoughtWorks December 10, 2008, Antwerp, Belgium xii | Foreword
📄 Page
10
Preface When I was presented with the opportunity to revise Java Message Service, I jumped at the chance. The first edition, published by O’Reilly in 2000, was a bestseller and without a doubt the definitive source for JMS and messaging in general at that time. Writing the second edition was an exciting chance to breath new life into an already great book and add new content that was relevant to how we use messaging today. What I failed to fully realize when I took on the project was just how much messaging (or, more precisely, how we use messaging) has changed in the past 10 years. New messaging techniques and technologies have been developed, including message- driven beans (as part of the EJB specification), the Spring messaging framework, Event- Driven Architecture, Service-Oriented Architecture, RESTful JMS interfaces, and the Enterprise Service Bus (ESB), to name a few. The somewhat minor book project that I originally planned quickly turned into a major book project. My original intent was to preserve as much of the original content as possible in this new edition. However, based on changes to the JMS specification since the first edition was written, as well as the development of new messaging techniques and technologies, the original content quickly shrank. As a result, you will find that roughly 75% of this second edition is new or revised content. The JMS specification was updated to version 1.1 a couple of years after the printing of the first edition of this book. While not a major change to the JMS specification, the JMS 1.1 specification was nevertheless a significant step toward fixing some of the deficiencies with the original JMS specification. One of the biggest changes in the spec- ification was the joining of the queue and topic API under a unified general API, allowing queues and topics to share the same transactional unit of work. However, the specification change alone was not the only factor that warranted a second edition of the book. As the Java platform has matured, so has the way we think about messaging. From new messaging technologies and frameworks to complex integration and throughput requirements, messaging has changed the way we think about and design systems, particularly over the past 10 years. These factors, combined with the specifi- cation changes, are the reasons for the second edition. xiii
📄 Page
11
With the exception of the Chat application found in Chapter 2, all of the sample code has been changed to reflect more up-to-date messaging use cases and to illustrate some additional features of JMS that were not included in the first edition. I added several new chapters that were not included in the first edition, for obvious reasons. You will find new sections in the first chapter on the JMS API, updated messaging use cases, and a discussion of how messaging has changed how we design systems. You will also find new chapters on message filtering, Java EE and message- driven beans, Spring JMS and message-driven POJOs, and messaging design. In addition to adding new chapters, I significantly revised the existing chapters. Because I updated the sample code used to illustrate various points throughout the book, I was in turn forced to rewrite much of the corresponding text. This provided me with the opportunity to add additional sections and topics, particularly in Chapter 4, Point-to- Point Messaging, and Chapter 5, Publish-and-Subscribe Messaging. I also reversed these chapters from the first edition with the belief that it is easier to jump into messaging with the point-to-point messaging model using queues rather than the publish-and- subscribe messaging model using topics and subscribers. I hope you find the new edition of this book helpful in terms of understanding the Java Message Service and messaging in general. —Mark Richards Who Should Read This Book? This book explains and demonstrates the fundamentals of Java Message Service. It provides a straightforward, no-nonsense explanation of the underlying technology, Java classes and interfaces, programming models, and various implementations of the JMS specification. Although this book focuses on the fundamentals, it’s no “dummy’s” book. While the JMS API is easy to learn, the API abstracts fairly complex enterprise technology. Before reading this book, you should be fluent with the Java language and have some practical experience developing business solutions. Experience with messaging systems is not required, but you must have a working knowledge of the Java language. Organization The book is organized into 11 chapters and 4 appendixes. Chapter 1 explains messaging systems, messaging use cases, centralized and distributed architectures, and why JMS is important. Chapters 2 through 6 go into detail about developing JMS clients using the two messaging models, point-to-point and publish-and-subscribe, including how to filter messages using message selectors. Chapters 7 and 10 should be considered “advanced topics,” covering deployment and administration of messaging systems. Chapter 8 provides an overview of the Java 2, Enterprise Edition (Java EE) with regard xiv | Preface
📄 Page
12
to JMS, including coverage of message-driven beans as part of the Enterprise JavaBeans 3.0 specification. Chapter 9 covers the Spring Framework as it relates to messaging. Finally, Chapter 11 provides some insight into many of the design considerations and anti-patterns associated with messaging. Chapter 1, Messaging Basics Defines enterprise messaging and common architectures used by messaging ven- dors. JMS is defined and explained, as are its two programming models, publish- and-subscribe and point-to-point. Many of the use cases and real-world scenarios for messaging are described in this chapter, as are the basics of the JMS API. Chapter 2, Developing a Simple Example Walks the reader through the development of a simple publish-and-subscribe JMS client. Chapter 3, Anatomy of a JMS Message Provides a detailed examination of the JMS message, the most important part of the JMS API. Chapter 4, Point-to-Point Messaging Examines the point-to-point messaging model through the development of a sim- ple borrower and lender JMS application. Also covers some of the finer points of the point-to-point messaging model, including message correlation, dynamic queues, load balancing, and queue browsing. Chapter 5, Publish-and-Subscribe Messaging Examines the publish-and-subscribe messaging model through the enhancement of the borrower and lender application developed in Chapter 4. This chapter also covers durable subscribers, nondurable subscribers, dynamic durable subscribers, and temporary topics. Chapter 6, Message Filtering Provides a detailed explanation of message filtering using message selectors. Chapter 7, Guaranteed Messaging and Transactions Provides an in-depth explanation of advanced topics, including guaranteed mes- saging, transactions, acknowledgments, message grouping, and failures. Chapter 8, Java EE and Message-Driven Beans Provides an overview of the Java 2, Enterprise Edition (Java EE) version 3.0 with regard to JMS and includes coverage of message-driven beans (MDBs). Chapter 9, Spring and JMS Provides a detailed explanation of the Spring Framework with regards to JMS, including the Spring JMS Template and message-driven POJOs (MDPs). Chapter 10, Deployment Considerations Provides an in-depth examination of features and issues that should be considered when choosing vendors and deploying JMS applications. Preface | xv
📄 Page
13
Chapter 11, Messaging Design Considerations Provides insight into and explanation of several design considerations, including the use of internal versus external destinations, request/reply processing, and a discussion of some of the more common messaging anti-patterns. Appendix A, The Java Message Service API Provides a quick reference to the classes and interfaces defined in the JMS package. Appendix B, Message Headers Provides detailed information about message headers. Appendix C, Message Properties Provides detailed information about message properties. Appendix D, Installing and Configuring ActiveMQ Provides detailed information about installing and configuring ActiveMQ to run the examples in this book. Software and Versions This book covers Java Message Service version 1.1. It uses Java language features from the Java 6 platform. Because the focus of this book is to develop vendor-independent JMS clients and applications, I have stayed away from proprietary extensions and vendor-dependent idioms. Any JMS-compliant provider can be used with this book; you should be familiar with that provider’s specific installation, deployment, and run- time management procedures to work with the examples. To find out the details of installing and running JMS clients for a specific JMS provider, consult your JMS ven- dor’s documentation; these details aren’t covered by the JMS specification. We have provided the details for running the examples with ActiveMQ, a popular open source JMS provider, in Appendix D. The source code examples and explanation in Chapter 8 refer to the Enterprise Java- Beans 3.0 (EJB 3) specification. The source code examples and explanation in Chap- ter 9 refer to version 2.5 of the Spring Framework The examples developed in this book are available through the book’s catalog page at http://oreilly.com/catalog/9780596522049/examples. These 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 for setting up the provider for each example. Conventions Used in This Book The following typographical conventions are used in this book: xvi | Preface
📄 Page
14
Italic Used for filenames, pathnames, hostnames, domain names, URLs, email ad- dresses, and new terms when they are defined. Constant width 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 Used for emphasis in some code examples. Constant width italic Used to indicate text that is replaceable. This icon signifies a tip, suggestion, or general note. The term JMS provider is used to refer to a vendor that implements the JMS API to provide connectivity to its 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. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example, “Java Message Service, Second Edition, by Mark Richards, Richard Monson-Haefel, and David A. Chappell. Copyright 2009 Mark Richards, 978-0-596-52204-9.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. Preface | xvii
📄 Page
15
Safari® Books Online When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf. Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://my.safaribooksonline.com/. How to Contact Us 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 Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, or any additional information. You can access this page at: http://www.oreilly.com/catalog/9780596522049/ To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com For more information about our books, conferences, software, Resource Centers, and the O’Reilly Network, see our website at: http://www.oreilly.com Acknowledgments These acknowledgments are from Mark Richards and refer to the second edition of this book. No one ever writes a book alone; rather, it is the hard work of many people working together that produces the final result. There are many people I would like to acknowl- edge and thank for the hard work and support they provided during the project. xviii | Preface
📄 Page
16
First, I would like to recognize and thank my editor, Julie Steele, for putting up with me during the project and doing such a fantastic job editing, coordinating, and every- thing else involved with getting this book to print. I would also like to thank Richard Monson-Haefel for doing such a great job writing the first edition of this book (along with David Chappell), and for providing me with the opportunity to write the second edition. To my good friend and colleague, Ted Neward, I want to thank you for writing the Foreword to this book during your very busy travel schedule and for providing me with insight and guidance throughout the project. Your suggestions and guidance helped bring this new edition together. I also want to thank my friends, Neal Ford, Scott Davis, Venkat Subramaniam, Brian Sletten, David Bock, Nate Shutta, Stuart Halloway, Jeff Brown, Ken Sipe, and all the other No Fluff Just Stuff (NFJS) gang, for your continued support, lively discussions, and camaraderie both during and outside the NFJS con- ferences. You guys are the greatest. I also want to thank the many expert technical reviewers who helped ensure that the material was technically accurate, including Ben Messer, a super software engineer and technical expert; Tim Berglund, principle software developer and owner of the August Technology Group, LLC; Christian Kenyeres, principle technical architect at Collab- orative Consulting, LLC; and last (but certainly not least), Ken Yu and Igor Polevoy. I know it wasn’t easy editing and reviewing the manuscript during the holiday season (bad timing on my part, I’m afraid), but your real-world experience, advice, comments, suggestions, and technical editing helped make this a great book. To the folks at the Macallan Distillery in Scotland, thank you for making the best single malt Scotch in the world. It helped ease the pain during those long nights of writing, especially during the winter months. Finally, I would like to acknowledge and thank my lovely wife, Rebecca, for her con- tinued support throughout this book project. You mean the world to me, Rebecca, and always will. Acknowledgments from the First Edition These acknowledgments are carried over from the first edition of this book and are from the original authors, Richard Monson-Haefel and David A. Chappell. While there are only two names on the cover of this book, the credit for its development and delivery is shared by many individuals. Michael Loukides, our editor, was pivotal to the success of this book. Without his experience, craft, and guidance, this book would not have been possible. Many expert technical reviewers helped ensure that the material was technically accu- rate and true to the spirit of the Java Message Service. Of special note are Joseph Fialli, Anne Thomas Manes, and Chris Kasso of Sun Microsystems; Andrew Neumann and Preface | xix
📄 Page
17
Giovanni Boschi of Progress; Thomas Haas of Softwired; Mikhail Rizkin of Interna- tional Systems Group; and Jim Alateras of ExoLab. The contributions of these technical experts are 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. Special appreciation goes to George St. Maurice of the SonicMQ tech writing team for his participation in organizing the examples for the O’Reilly website. Finally, the most sincere gratitude must be extended to our families. Richard Monson- Haefel thanks his wife, Hollie, for supporting and assisting him through yet another book. Her love makes everything possible. David Chappell thanks his wife, Wendy, and their children, Dave, Amy, and Chris, for putting up with him during this endeavor. David Chappell would also like to thank some of the members of the Progress SonicMQ team—Bill Wood, Andy Neumann, Giovanni Boschi, Christine Semeniuk, David Grigglestone, Bill Cullen, Perry Yin, Kathy Guo, Mitchell Horowitz, Greg O’Connor, Mike Theroux, Ron Rudis, Charlie Nuzzolo, Jeanne Abmayr, Oriana Merlo, and George St. Maurice—for helping to ensure that the appropriate topics were addressed, and addressed accurately. And special thanks to George Chappell for helping him with “split infinitives.” xx | Preface
📄 Page
18
CHAPTER 1 Messaging Basics Over the years, systems have grown significantly in terms of complexity and sophisti- cation. The need to have systems with better reliability, increased scalability, and more flexibility than in the past has given rise to more complex and sophisticated architec- tures. In response to this increased demand for better and faster systems, architects, designers, and developers have been leveraging messaging as a way of solving these complex problems. Messaging has come a long way since the first edition of this book was published in 2000, particularly with respect to the Java platform. Although the Java Message Service (JMS) API hasn’t changed significantly since its introduction in 1999, the way messag- ing is used has. Messaging is widely used to solve reliability and scalability issues, but it is also used to solve a host of other problems encountered with many business and nonbusiness applications. Heterogeneous integration is one primary area where messaging plays a key role. Whether it be through mergers, acquisitions, business requirements, or simply a change in technology direction, more and more companies are faced with the problem of in- tegrating heterogeneous systems and applications within and across the enterprise. It is not unusual to encounter a myriad of technologies and platforms within a single company or division consisting of Java EE, Microsoft .NET, Tuxedo, and yes, even CICS on the mainframe. Messaging also offers the ability to process requests asynchronously, providing archi- tects and developers with solutions for reducing or eliminating system bottlenecks, and increasing end user productivity and overall system scalability. Since messaging pro- vides a high degree of decoupling between components, systems that utilize messaging also provide a high degree of architectural flexibility and agility. Application-to-application messaging systems, when used in business systems, are generically referred to as enterprise messaging systems, or Message-Oriented Middle- ware (MOM). Enterprise messaging systems allow two or more applications to ex- change 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 1
📄 Page
19
a message can be anything—depending on the business scenario—and usually contains information about some business transaction. In enterprise messaging systems, mes- sages 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. Enterprise middleware products ensure that messages are properly distributed among applications. In addition, these products usually provide fault tolerance, load balancing, scalability, and transactional support for enterprises that need to reliably exchange large quantities of messages. Enterprise messaging vendors use different message formats and network protocols for exchanging messages, but the basic semantics are the same. An API is used to create a message, load the application data (message payload), assign routing information, and send the message. The same API is used to receive messages produced by other applications. In all modern enterprise messaging systems, applications exchange messages through virtual channels called destinations. When a message is sent, it’s addressed to a desti- nation (i.e., queue or topic), not a specific application. Any application that subscribes or registers an interest in that destination may receive the message. In this way, the applications that receive messages and those that send messages are decoupled. Senders and receivers are not bound to each other in any way and may send and receive messages as they see fit. All enterprise messaging vendors provide application developers with an API for send- ing and receiving messages. While a messaging vendor implements its own networking protocols, routing, and administration facilities, the basic semantics of the developer API provided by different vendors are the same. This similarity in APIs makes the Java Message Service possible. JMS is a vendor-agnostic Java API that can be used with many different enterprise messaging vendors. JMS is analogous to JDBC in that application developers reuse the same API to access many different systems. If a vendor provides a compliant service provider for JMS, the JMS API can be used to send and receive messages to that vendor. For example, you can use the same JMS API to send messages using SonicMQ that you would using IBM’s WebSphere MQ. It is the purpose of this book to explain how enterprise messaging systems work and, in particular, how JMS is used with these sys- tems. The second edition of this book focuses on JMS 1.1, the latest version of the specification, which was introduced in March 2002. The rest of this chapter explores enterprise messaging and JMS in more detail, so that you have a solid foundation with which to learn about the JMS API and messaging concepts in later chapters. The only assumption we make in this book is that you are already familiar with the Java programming language. 2 | Chapter 1: Messaging Basics
📄 Page
20
The Advantages of Messaging As stated at the beginning of this chapter, messaging solves many architectural chal- lenges such as heterogeneous integration, scalability, system bottlenecks, concurrent processing, and overall architecture flexibility and agility. This section describes the more common advantages and uses for JMS and messaging in general. Heterogeneous Integration The communication and integration of heterogeneous platforms is perhaps the most classic use case for messaging. Using messaging you can invoke services from applica- tions and systems that are implemented in completely different platforms. Many open source and commercial messaging systems provide seamless connectivity between Java and other languages and platforms by leveraging an integrated message bridge that converts a message sent using JMS to a common internal message format. Examples of these messaging systems include ActiveMQ (open source) and IBM WebSphere MQ (commercial). Both of these messaging systems support JMS, but they also expose a native API for use by non-Java messaging clients (such as C and C++). The key point here is that, depending on the vendor, it is possible to use JMS to communicate to non- Java or non-JMS messaging clients. Historically, there have been many ways of tackling the issue of heterogeneous systems integration. Some earlier solutions involved the transfer of information through FTP or some other file transfer means, including the classic “sneakernet” method of carrying a diskette or tape from one machine to another. Using a database to share information between two heterogeneous systems or applications is another common approach that is still widely used today. Remote Procedure Call, or RPC, is yet another way of sharing both data and functionality between disparate systems. While each of these solutions have their advantages and disadvantages, only messaging provides a truly decoupled solution allowing both data and functionality to be shared across applications or sub- systems. More recently, Web Services has emerged as another possible solution for integrating heterogeneous systems. However, lack of reliability for web services make messaging a better integration choice. Reduce System Bottlenecks System and application bottlenecks occur whenever you have a process that cannot keep up with the rate of requests made to that process. A classic example of a system bottleneck is a poorly tuned database where applications and processes wait until database connections are available or database locks free up. At some point the system backs up, response time gets worse, and eventually requests start timing out. A good analogy of a system bottleneck is pouring water into a funnel. The funnel be- comes a bottleneck because it can only allow a certain amount of water to pass through. As the amount of water entering the funnel increases, the funnel eventually overflows The Advantages of Messaging | 3
The above is a preview of the first 20 pages. Register to read the complete e-book.