Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

Asynchronous Messaging with WebLogic Server, Server Sessions, and MDBs

Asynchronous Messaging with WebLogic Server, Server Sessions, and MDBs

A synchronous message processing is a requirement of many applications that need to send and receive messages in real time or near real time. The JMS 1.0.2 Specification defines the MessageListener interface that allows an application to receive messages asynchronously from a JMS Destination when a message is sent to that destination. An implementation of the MessageListener interface is typically a client application to a JMS provider that runs in a remote JVM.

The JMS Specification also defines an optional set of APIs, JMS Application Server Facilities, that may be implemented by an application server vendor to allow for asynchronous, concurrent processing of a subscription. The EJB 2.0 Specification provides the Message Driven Bean API (MDB) that allows a developer to create and deploy a component into an EJB container, and have the container invoke the MDB when a message is sent to a JMS Destination that the MDB is deployed to service. Both of these APIs provide a way to consume messages from a JMS Destination within the JVM and framework of an application server rather than as an external JMS client to a JMS provider. Consumers deployed in this fashion can take advantage of services provided by the application server, such as transaction and thread management.

WebLogic Application Server provides an implementation of the MDB API described in the EJB 2.0 Specification and the optional JMS Application Server Facilities described in Chapter 8 of the JMS 1.0.2 Specification. I'll discuss these APIs, and support for them within WebLogic Server, with a store and forward example that uses MDB and ServerSessionPool. The example code was developed and tested using WebLogic Server 6.0 Service Pack 2. A general discussion of JMS isn't provided here, but an excellent three-part article, authored by Dave Chappell, on the JMS API can be found in the March, April, and May 2001 issues of Java Developer's Journal (Vol. 6, issues 3-5).

JMS ServerSessions
Chapter 8 of the JMS 1.0.2 Specification defines three additional optional interfaces, implemented by an application server vendor, that provide a special facility for concurrent message processing. It further delineates the roles of JMS provider, Application Server, and Application regarding the implementation and use of these interfaces. The interfaces found in the javax.jms package that make up this part of the API are ServerSession, ServerSessionPool, and ConnectionConsumer. The spec also defines how an application server will use the javax.jms.Session interface to implement these special facilities.

A Session object provides a setMessageListener() and getMessageListener() method to allow a ConnectionConsumer to associate a MessageListener with a Session. The ConnectionConsumer can set the MessageListener with a message selector. It also provides a run() method that allows an application server to start a Session once messages are available for consumption on a Destination.

A ServerSession is implemented by the application server to provide the runtime support for a JMS Session. It maps a thread to a Session and executes the Session's run() method through its start() method. In addition to the start() method, the ServerSession defines a getSession() method that returns the JMS Session associated with the ServerSession to the caller.

The application server also provides a javax.jms.ServerSessionPool object that's used by the ConnectionConsumer to get a Session for message processing. The ConnectionConsumer uses the only ServerSessionPool method, getServerSession(), to acquire a ServerSession for consuming messages that have been produced at the Destination.

Finally, javax.jms.TopicConnection and javax.jms.QueueConnection provide a method, getConnectionConsumer(), that creates a ConnectionConsumer that's used by the application server to load messages into a Session, and start the Session indirectly by calling the ServerSession's start() method. Construction of the ConnectionConsumer associates it with a ServerSessionPool and a Destination.

WebLogic provides an additional class that isn't part of the specification, weblogic.jms.ServerSessionPoolFactory. A ServerSessionPoolFactory is a factory pattern used to create a ServerSessionPool and associate it with a Connection, a MessageListener, set the Session's acknowledgment type, and define the transaction semantics of the Session. Implementation of a ServerSessionPool is subject to interpretation and will have vendor-specific features, and as such, its life cycle is well-suited to the factory pattern should the implementation change or should multiple implementations be made available. The WebLogic Server ServerSessionPool factory is looked up through JNDI using the name "weblogic.jms.ServerSessionPoolFactory:<name>" where <name> is the name of the JMS Server where the ServerSessionPool will be used.

MDBs
Message Driven Beans are defined by the EJB 2.0 Specification and exist for the exclusive purpose of consuming messages from a JMS Destination. WebLogic Server 6.0 provides full support for the MDB portion of the EJB 2.0 API.

If you are a seasoned EJB developer, MDBs are surprisingly simple, and even if you are new to EJB development you can create and deploy MDBs to consume messages from JMS Destinations with little difficulty. This simplicity of development and deployment is, in my opinion, the strong suit of MDBs.

Unlike session beans and entity beans, an MDB doesn't require the development of an extension to the EJBHome interface or the EJBObject interface. The reasons are that an MDB's home interface isn't located by a client application through a JNDI lookup, its life cycle isn't controlled by a client application through the factory methods on a home interface, and no methods need to be exposed to a client application through a remote interface. All the bean developer needs to do is implement the MessageDrivenBean interface with its two methods, setMessageDrivenContext() and ejbRemove() and implement the MessageListener interface providing an onMessage() implementation.

The spec adds some new elements to the ejb-jar.xml deployment descriptor for deploying MDBs. Here's the element definition from the ejb-jar_2.0.dtd:

<!ELEMENT message-driven (description?, display-name?, small-icon?, large-icon?, ejb-name?, ejb-class, transaction-type, message-selector?, acknowledge-mode?, message-driven-destination?, env-entry*, ejb-ref*, security-identity?, resource-ref*, resource-env-ref*)>

The <message-driven> element is an optional element contained in the <enterprise-beans> element. It uses many of the elements previously defined for describing an EJB, such as <ejb-name> and <transaction-type>. The <transaction-type> element describes the transaction semantics of the bean. The allowable values are "Bean" and "Container", analogous to session beans. A value of "Container" tells the EJB container to call the MDB onMessage() method in the context of a transaction. This is recommended. When using container-managed transactions, a <container-managed> section in the <assembly-descriptor> is required to tell the container what transaction attributes are needed for the MDB when it's invoked. When using container-managed transactions, the allowable values for <trans-attribute> are "Required" and "NotSupported". The new elements defined are:

  • <message-driven-destination>
  • <message-selector>
  • <acknowledge-mode>
The <message-driven-destination> element is a stanza used to describe the characteristics of the destination the MDB is deployed to consume. It must contain <destination-type> and may optionally contain <subscription durability>. The allowable values for <destination-type> are "javax.jms.Queue" and "javax.jms.Topic". The allowable values for <subscription-durability> are "Durable" and "NonDurable", with "NonDurable" being the default.

A <message-selector> may be specified using message selector syntax described in the JMS Specification. Message selection with MDBs is discouraged, as it can be an expensive operation when there are many messages in a Queue or Topic. Message selectors on Queues are not recommended.

Message Driven Beans do not use the JMS message acknowledgment API. The container provides message acknowledgment for the MDB based on the value of <acknowledge-mode> in the deployment descriptor. The default mode is AUTO_ACKNOWLEDGE.

The weblogic-ejb-jar.dtd also defines a new element, <message-driven-descriptor>, that's used to specify WebLogic Server-specific properties of the bean at deployment time. It's defined as:

<!ELEMENT message-driven-descriptor (
pool?,
destination-jndi-name?,
initial-context-factory?,
provider-url?,
connection-factory-jndi-name?
)
>

The <pool> element is used to tell the container how to pool instances of the MDB. The <destination-jndi-name> is the name of the Destination that the MDB will consume messages on. The <initial-context-factory> is the name of the JNDI InitialContext factory that will be used to get an InitialContext for looking up a ConnectionFactory. The <provider-url> is the URL of the InitialContext provider, and the <connection-factory-jndi-name> is the name of the ConnectionFactory that will be looked up.

Store and Forward Example
I created a small store and forward example to demonstrate the use of these two server-side techniques of asynchronous messaging. I developed the example by taking sample code provided with WebLogic Server and changing it slightly, and by using the WebLogic Server Admin Console to create the necessary JMS elements (see Figure 1).

The example uses a Queue and two Topic(s) to simulate a store and forward architecture used to route alarm messages. The Queue is consumed by an MDB that examines the header of a TextMessage for information that the MDB uses to forward the message to the appropriate Topic. The header contains a criticality level for the alarm message used for routing. The two Topic(s) represent forward destinations for the two levels of alarm criticality. One Topic receives "Critical" alarms and the other Topic receives "Normal" alarms (see Figure 2).

Alarm Routing MDB
The "Alarm" Queue, wldjAlarmQueue, is a persistent Queue that's consumed by the AlarmReaderBean class that implements MessageDrivenBean and MessageListener. The AlarmReaderBean is deployed with container-managed transactions and a <transaction-attribute> of "Required". The ejb-jar.xml and weblogic-ejb-jar.xml deployment descriptors are shown in Listings 1 and 2.

The onMessage() method of this consumer is responsible for examining a user property named "level" in the message header and forwarding the message to the wldjCriticalAlarmTopic or the wldjNormalAlarmTopic (see Listing 3).

Since the onMessage() method has to route the message to the appropriate Topic, it must have access to a TopicConnection to do so. To avoid looking up a TopicConnection every time a message is processed, the ejbCreate() method of the AlarmReaderBean performs a JNDI lookup on the wldjTopicConnectionFactory, creates a TopicConnection, and starts the TopicConnection. The ejbCreate() method is called only when the WebLogic Server EJB container creates the bean instance (see Listing 4).

When the onMessage() method has decided where to route the message, it creates a nontransacted AUTO_ACKNOWLEDGE TopicSession using the cached TopicConnection. It uses the TopicSession to create a TopicPublisher and then publish the message to the found Topic. The TopicPublisher and TopicSession are closed at the end of the method.

Consumer ServerSessions
Once the alarm messages have been routed to the wldjCriticalAlarmTopic and the wldjNormalAlarmTopic, they are processed by a MessageListener that has been associated with the Sessions in the ServerSessionPool. When the message arrives, the ConnectionConsumer assigned to the Destination uses the ServerSessionPool to acquire a ServerSession and a Session, loads the Session with a message (one or more), and starts the ServerSession. Let's examine the ServerSessionPool and ConnectionConsumer for the wldjCriticalAlarmTopic.

A ServerSessionPool and ConnectionConsumer can be created programmatically or by using the WebLogic Server Admin Console. Programmatically creating the ServerSessionPool and ConnectionConsumer can be done from a WebLogic Server client application or from a WebLogic Server Startup class.

Example code of creating and initializing a ServerSessionPool and a ConnectionConsumer in a Startup class is provided with the WebLogic Server distribution in WL_HOME/samples/examples/jms/sessionpool and WL_HOME/samples/examples/jms/startup where WL_HOME is the directory where the WebLogic Server installation is located. A Startup class is a class that implements weblogic.common. T3StartupDef is deployed in a WebLogic Server server instance and is invoked by WebLogic Server at the end of the startup sequence to perform any task that logically needs to be performed at server startup, such as ServerSessionPool initialization. See listing 5 for the example modified for our application.

First, a Connection to the JMS Server must be acquired through a ConnectionFactory. I used a Topic, a TopicConnection, and a TopicConnectionFactory for this example. A default implementation of TopicConnectionFactory is provided by WebLogic Server and can be found through a JNDI lookup. I created my own TopicConnectionFactory, wldjTopicConnectionFactory, with the same characteristics as the default.

Next, a JNDI lookup is performed on the Topic that the ConnectionConsumer will service. A JNDI lookup is performed to locate the ServerSessionPoolFactory, and from the factory a SessionPool is acquired using the getServerSessionPool() method. It's important to note that the SessionPool is created by passing a Connection, the maximum number of Sessions in the pool, a class that implements the MessageListener interface, a Boolean that specifies if the Sessions are transacted or nontransacted, and an acknowledgment mode to the getServerSessionPool() method. Finally, the ConnectionConsumer is created using the createConnectionConsumer() method on the Connection object, and is passed to the Topic, the ServerSessionPool, a message selector String, and the maximum number of messages that can be loaded into a Session. The message selector specified when the ConnectionConsumer is created using a String containing the message selector syntax defined in the JMS Specification. My example uses '"TRUE" as the message selector that selects all messages. More on this later.

The Startup class will execute at the end of WebLogic Server initialization and prepare a ConnectionConsumer that's ready to load a JMS Session with messages from the Topic and start the Session so that the messages can be consumed by the specified MessageListener. When a message arrives at the Destination, the ConnectionConsumer gets a ServerSession, uses the ServerSession to get the JMS Session, loads the JMS Session with one or more messages, and calls the start() method on the ServerSession. The ServerSession calls the run() method on the JMS Session, which then calls the onMessage() method of the associated MessageListener, passing it the Message that needs to be consumed. The role of the ConnectionConsumer is diagrammed in the JMS Specification and reproduced in Figure 3.

I find the programmatic technique of creating a ServerSessionPool and ConnectionConsumer much more complicated than using the WebLogic Server Admin Console. They can be created in the Admin Console after the JMS Server has been created. Use the SessionPools tab under JMS->Servers>yourServer NameSessionPools. Select "Create a new JMS Session PoolS". That will take you to the frame that allows you to specify the characteristics of the ServerSessionPool (see Figure 4).

The wldjCriticalTopicSessionPool specifies the wldjTopicConnectionFactory as the ConnectionFactory to use, the fully qualified classname of the MessageListener, wldj.jms.AlarmListener, the Acknowledgment Mode as Auto, the maximum number of Sessions, and the transaction semantics of the Sessions. All that must be provided programmatically is the MessageListener, which has to be provided if you create the ServerSessionPool programmatically as well.

Next, create the ConnectionConsumer by navigating to the Consumers tab under the newly created ServerSessionPool (see Figure 5). The ConnectionConsumer is configured with the maximum number of messages that it should load into a Session, a message selector, and the Destination for which it is consuming messages.

When messages arrive at the wldjCriticalTopicConnection, the ConnectionConsumer gets a JMS Session from a ServerSession in the ServerSessionPool, loads the Session with a message, and starts the ServerSession. The ServerSession then calls the run() method on the Session, which activates the onMessage() method of the associated MessageListener and passes it a Message.

QueueSend Client
This application passes a TextMessage from a "store" queue, wldjAlarmQueue, to "forward" Topics, wldjCriticalAlarmTopic, and wldjNormalAlarmTopic. To get the TextMessage to the wldjAlarmQueue, a JMS client that uses a QueueSender was created. The client sets the JMS MessagePriority, sets a String header property named "level", and sets a String into the TextMessage (see Listing 6).

Transactions
Transaction semantics in the JMS Specification are associated with the Session object. A Session can be created as transacted or nontransacted. Transacted Sessions have their transactions committed or rolled back with the commit() and rollback methods. Nontransacted Sessions are created with an acknowledgment mode specified.

When using server-side asynchronous message consumers, MDBs or ServerSessionPools, using nontransacted Sessions with an acknowledge mode of AUTO_ACKNOWLEDGE allows the JMS server to manage the transactions for the message consumer by calling its onMessage() method in the context of a transaction, and then committing the transaction when the onMessage() method returns. If you use transacted Sessions, your MessageConsumer is responsible for committing or rolling back the transaction.

JTA User Transactions aren't supported with MDB. A JTA User Transaction started in the onMessage() method of a MessageConsumer called by a Session in a ServerSessionPool will be outside of the context of the transaction started when the onMessage() method is called.

Summary
An asynchronous message-processing application can take advantage of the JMS and EJB APIs to perform message processing using just server-side code that runs in the framework of WebLogic Server. This releases client code from having to manage threads, concurrency, and transactions. The ease of creating this store and forward example is a testament to the robust implementation of the JMS and Message Driven Bean APIs by WebLogic Server.

ServerSessionPools and ConnectionConsumers are presented here as an alternative to using MDBs, but are more involved in their implementation. MDB is a simpler choice with the restriction that only one MDB can be deployed per Destination. Multiple ServerSessionPools and ConnectionConsumers can be created to service one Destination, and each ConnectionConsumer can be deployed with a message selector to filter messages based on Message header properties. Message selectors are expensive and not recommended on Queues, but may be useful to filter messages on a Topic that may have more than one interested subscriber or that may be consumed by more than one ConnectionConsumer. Message filtering on a Queue by an MDB should be performed programmatically in the MessageListener's onMessage() method, as was shown by the AlarmReaderBean.

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.


@ThingsExpo Stories
BnkToTheFuture.com is the largest online investment platform for investing in FinTech, Bitcoin and Blockchain companies. We believe the future of finance looks very different from the past and we aim to invest and provide trading opportunities for qualifying investors that want to build a portfolio in the sector in compliance with international financial regulations.
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
Imagine if you will, a retail floor so densely packed with sensors that they can pick up the movements of insects scurrying across a store aisle. Or a component of a piece of factory equipment so well-instrumented that its digital twin provides resolution down to the micrometer.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settle...
Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
We are given a desktop platform with Java 8 or Java 9 installed and seek to find a way to deploy high-performance Java applications that use Java 3D and/or Jogl without having to run an installer. We are subject to the constraint that the applications be signed and deployed so that they can be run in a trusted environment (i.e., outside of the sandbox). Further, we seek to do this in a way that does not depend on bundling a JRE with our applications, as this makes downloads and installations rat...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...