IBM Cloud Authors: Yeshim Deniz, Elizabeth White, Zakia Bouachraoui, Pat Romanski, Liz McMillan

Related Topics: IBM Cloud

IBM Cloud: Article

Enterprise Messaging Using JMS and IBM WebSphere

Enterprise Messaging Using JMS and IBM WebSphere

Having established an understanding of our unit of exchange - the message - we are now ready to delve into the mechanics of messaging using the JMS API. In this chapter we begin with a discussion on implementation choices, examining our options regarding the software components with which we might implement a JMS client. We then undertake a detailed review of the JMS API, using code snippets to illustrate usage and implementation approaches. We do this by examining in turn each set of interfaces: point-to-point, publish-subscribe, and the unified or common interface. This will round out our knowledge of JMS and prepare us to consider a number of real-world scenarios based on a specific product family: IBM WebSphere.

The JMS client is the entity that utilizes the JMS API to interact with the JMS provider. It can be any Java artifact, and depending on the application environment, a number of choices exist as to how the JMS client is implemented. The JMS client could be a standalone Java application, serving as part of a desktop client, or acting as the connectivity module (adapter) for a business application. The JMS client could also be encapsulated in a J2EE component such as an applet, servlet or portlet, or Enterprise JavaBean (EJB). That the JMS client can be any Java artifact offers a great deal of flexibility in implementation. However, this comes at a price, as the deci-sion-making process regarding your implementation choice becomes more involved.

The choice between a standalone Java application or J2EE component is one we need not address, as that decision is driven more by the nature of the application and its target runtime environment than by the JMS connectivity requirement. However, if the application is J2EE-based, then we still have the basic choices of applet, servlet, or EJB.

Servlets and EJBs are server-side components that run in containers in the J2EE server. They consequently have access to a host of services, such as security and transaction support (see Chapter 2, "Java Message Service"). Applets, on the other hand, are client-side (presentation layer) components that run in a browser and are most often used as user interface constructs. Current best practice recommends that J2EE applications adopt a lightweight presentation layer with business logic and connectivity to enterprise resources (such as messaging providers) residing in server-side components. This enables transaction and security services to be readily invoked if required and offers an important advantage in that it is much easier to scale and modify serverside components. Furthermore, it greatly simplifies the implementation of the presentation layer.

With this in mind, it is fair to say that applets are probably least suited to the role of JMS client. Besides the design considerations, there are practical implications to be considered as well. The applet needs access to the JMS libraries (standard and provider implementation), increasing its size and potentially impacting the time it takes it to download to the browser. In addition, the still existing inconsistencies in browser Java Virtual Machines (JVMs) and their support for running JMS must be addressed. Such inconsistencies can complicate the deploy-ment of the solution and force you to have to specify browser versions or runtime plug-ins that will support your application. In solutions where applets are used (their current popularity is questionable), a better pattern is for the applet to call a servlet. The servlet then either calls an EJB, which implements the JMS client, or it implements the JMS client itself.

In deciding whether to implement the JMS client in a servlet/portlet or EJB, consider the following key questions:

  • Does your programming model currently use EJBs?
  • Is your application Web based?
  • Based on your application design, where does business logic reside?
  • Is the interaction with the JMS provider going to be transactional, potentially involving other resources?
  • If it is transactional, do you want to use container managed or client-demarcated transactions?
  • What is your considered approach to scaling your solution, particularly access to the JMS provider?
  • Which interaction patterns will your JMS client implement?

J2EE best practice recommends that connectivity logic - that is, access to enterprise resources - reside in the business logic layer, which in J2EE is the EJB layer. This suggests that EJBs should be the first choice when implementing the JMS client. However, for Web-based applications, it is not uncommon to find the JMS client being implemented by a servlet or portlet, since they offer a simpler programming framework when compared to EJBs. If transactions are required, then the only choice open to the servlet developer is the use of client-demarcated transactions. This requires that the developer explicitly handle the transactions, making appropriate Java Transaction API (JTA) calls such as commit or rollback at the right time. In contrast, the EJB developer has the option of having transactions managed by the container, which simply involves specifying the scope of the transaction as part of the deployment properties and requires no explicit programming. This greatly simplifies building transactional components and is considered a best practice.

In comparison to servlets, EJBs offer considerable tuning options and efficiency savings in terms of how the EJB container manages its EJBs and, by extension, access to enterprise resources. The EJB container can be expected to provide pooling optimizations, load-balancing configurations, and other scalability and performance enhancements, which can have consider-able benefits in terms of the scalability and reliability of the implemented solution. In addition, access to EJBs often tends to be more secure.

Recall from our discussion in Chapter 1, "Enterprise Messaging," that the interaction between the JMS client and the provider is composed of three base patterns: message producer, message consumer, and request-reply.

The message producer pattern involves simply sending a message; interaction with the provider ends once the message has been accepted by the provider. The session EJB readily lends itself to the role of message producer, being for the most part a stateless bean that can be reused by client applications such as servlets for sending messages. The same can be said for servlets, and here the choice is influenced by additional factors previously discussed, such as transaction requirements. For example, if the sending of the message is to occur as part of a global transaction, such as updating a database within the same transaction, then the container-managed transaction services offered by the EJB container further facilitate the implementation of this pattern.

The message consumer pattern is initiated by the arrival of a message. As discussed in Chapter 1, this initiation could occur in either a pull or push mode. In the pull mode, the application checks (polls) the messaging provider at suitable time intervals for a message. In the push mode, the messaging provider invokes the application when a message arrives, passing it the message. EJB 2.0 (included in J2EE 1.3) introduced support for implementing the message consumer pattern using EJBs by defining the message-driven bean (MDB). MDB support implements the message consumer pattern in push mode. The EJB container monitors the JMS destination using Application Server Facilities, or ASF (see Chapter 2) and invokes the MDB with a retrieved message as messages arrive.

In support of this facility, JMS defines a MessageListener interface, which the MDB implements. The MessageListener interface (discussed in the next section) was available before the advent of MDBs and can be used by servlets or other Java entities to implement the message consumer pattern. When the MessageListener interface is used by components other than MDBs, the JMS provider monitors the destination and invokes the component with the message on arrival. The use of MDBs, however, offers a number of distinct advantages. Using ASF, the EJB container can process multiple incoming messages from multiple destinations concurrently, providing a significant performance benefit. In contrast, the JMS provider can provide only serialized access to messages and destinations for other components using the MessageListener interface. In addition, the EJB container provides tuning, transaction, and message redelivery configuration options, which would have to be explicitly programmed into non-MDB entities.

It is useful to remember, however, that prior to J2EE 1.3 and EJB 2.0, none of this support existed, and the only option available to implement a push-mode message consumer was the MessageListener interface. The push-mode (some might say asynchronous) nature of the MessageListener interface does not readily lend itself to implementation using session EJBs, and thus prior to EJB 2.0, it was particularly difficult to implement the message consumer pattern using EJBs. A common workaround at the time was to have another component, typically a standalone application or servlet, monitor the JMS destination for a message and either retrieve and pass the message to the session bean or notify the session bean that a message was available for retrieval (used if retrieval needed to occur as part of a transaction managed by the EJB container).

The request-reply pattern combines the message producer and message consumer patterns to implement a conversation between the sending and receiving applications. There are two basic variations for this pattern (see Chapter 1). In the first, the requester (acting as a message producer) sends the request, then reverts to the role of message consumer and waits for its reply (pull mode). In the second variation, the requester sends the request, but a different component receives (consumes) the replies, usually operating in a push mode.

With the first variation, a critical factor is the length of time that the requester will wait for a reply to its request. JMS provides a receive method (more on this later in the chapter) that can have a wait time specified. The method returns with a message if it is available or with nothing after the specified wait time if no message has arrived. During the wait interval, the calling thread is blocked, and this is of particular importance if a session EJB is used to implement this pattern. Certain schools of thought totally abhor the concept of a blocked thread within the EJB container, particularly when it is considered that a large number of instances (blocked threads) of the session EJB can potentially exist. Consequently, when a session EJB is used in this manner, careful consideration must be given to the amount of time (specified in milliseconds) the session EJB will be allowed to wait and the impact that may have on the J2EE Server environment.

The second variation avoids this issue, as the requester session EJB doesn't wait for the reply and thus never blocks. The MDB readily lends itself to acting as the consumer of replies and, when paired with the requesting session EJB, provides a straightforward implementation for this variation.

We have detailed a number of considerations that should influence our choice of whether to use servlets or EJBs for JMS client implementations. All things considered, I recommend that JMS clients be implemented using EJBs. On the other hand, in cases where EJBs are not part of the adopted programming model and transactions (particularly global transactions involving other resources) are not required, servlets may prove attractive. However, as with all design decisions, the choice of what software component to use, is further constrained by factors directly associated with the nature of the project. Consequently, it is important to note that regardless of the entity adopted to implement the JMS client, the JMS API is used in the same way, and we examine its use in the following sections.

Point-to-Point Interface

As discussed in Chapter 1, point-to-point messaging is adopted when there is a one-to-one relationship between sender and receiver. In this message distribution pattern, the sender sends the message to a known destination, from where it is retrieved. Common usage scenarios include submitting an order or registration request to a processing application, effecting an account inquiry or update, and exchanging data between two systems that are being synchronized. JMS supports this message distribution pattern with a specific subset of the API that supports the semantics of point-to-point messaging. We examine the API by considering the three basic phases our JMS client will experience: connecting to a provider, producing a message, and consuming a message.

Connecting to a Provider
Connectivity to a provider is based on a QueueConnectionFactory, which contains the configuration details required to connect to the provider. As discussed in Chapter 2, the QueueConnectionFactory, a JMS-administered object, should be retrieved from a JNDI namespace. It is of course possible to create a provider-specific QueueConnectionFactory in code, but as this compromises the JMS client's portability and is not a recommended JMS practice, we will not explore that option further. Rather, we assume that a QueueCon-nectionFactory has been defined and stored in a given JNDI namespace, using a provider-specific administration tool (we explore how this is achieved in Chapter 6, "IBM JMS-Administered Objects"). Our first task is thus to establish a context to the JNDI namespace.

Creating an Initial Context
JNDI offers a rich API, but from the JMS client's perspective, we are interested in creating an InitialContext object with which we can look up named objects, specifically the Queue-ConnectionFactory. The InitialContext class acts as a starting point for accessing the naming system (namespace) and is created thus:

import javax.jms.*; // JMS classes
import java.io.*; // Standard Java imports import java.util.*;
import javax.naming.*; // JNDI imports ......
String jmsICF = "com.sun.jndi.fscontext.RefFSContextFactory";
String jmsURL = "file:/c:/JNDINamespace";
//connect to JNDI Namespace
Hashtable environment = new Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY, jmsICF);
environment.put(Context.PROVIDER_URL, jmsURL);
Context ctx = new InitialContext(environment);

More Stories By Kareem Yusuf

Kareem Yusuf, IBM Technical Sales Professional, has technical leadership responsibilities for JMS and IBM WebSphere customer implementations. He previously served as Technical Team Lead for WebSphere MQ JMS in IBM's WebSphere MQ Technical Support (Service) Organization at Hursley, UK. He has been working with WebSphere, JMS, and related enterprise messaging technologies since 1998.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
CloudEXPO has been the M&A capital for Cloud companies for more than a decade with memorable acquisition news stories which came out of CloudEXPO expo floor. DevOpsSUMMIT New York faculty member Greg Bledsoe shared his views on IBM's Red Hat acquisition live from NASDAQ floor. Acquisition news was announced during CloudEXPO New York which took place November 12-13, 2019 in New York City.
Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
Intel is an American multinational corporation and technology company headquartered in Santa Clara, California, in the Silicon Valley. It is the world's second largest and second highest valued semiconductor chip maker based on revenue after being overtaken by Samsung, and is the inventor of the x86 series of microprocessors, the processors found in most personal computers (PCs). Intel supplies processors for computer system manufacturers such as Apple, Lenovo, HP, and Dell. Intel also manufactu...
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
OpsRamp is an enterprise IT operation platform provided by US-based OpsRamp, Inc. It provides SaaS services through support for increasingly complex cloud and hybrid computing environments from system operation to service management. The OpsRamp platform is a SaaS-based, multi-tenant solution that enables enterprise IT organizations and cloud service providers like JBS the flexibility and control they need to manage and monitor today's hybrid, multi-cloud infrastructure, applications, and wor...
Apptio fuels digital business transformation. Technology leaders use Apptio's machine learning to analyze and plan their technology spend so they can invest in products that increase the speed of business and deliver innovation. With Apptio, they translate raw costs, utilization, and billing data into business-centric views that help their organization optimize spending, plan strategically, and drive digital strategy that funds growth of the business. Technology leaders can gather instant recomm...
The Master of Science in Artificial Intelligence (MSAI) provides a comprehensive framework of theory and practice in the emerging field of AI. The program delivers the foundational knowledge needed to explore both key contextual areas and complex technical applications of AI systems. Curriculum incorporates elements of data science, robotics, and machine learning-enabling you to pursue a holistic and interdisciplinary course of study while preparing for a position in AI research, operations, ...
After years of investments and acquisitions, CloudBlue was created with the goal of building the world's only hyperscale digital platform with an increasingly infinite ecosystem and proven go-to-market services. The result? An unmatched platform that helps customers streamline cloud operations, save time and money, and revolutionize their businesses overnight. Today, the platform operates in more than 45 countries and powers more than 200 of the world's largest cloud marketplaces, managing mo...