• No results found

JMS and MDB Java Message Services

N/A
N/A
Protected

Academic year: 2022

Share "JMS and MDB Java Message Services"

Copied!
97
0
0

Loading.... (view fulltext now)

Full text

(1)

JMS and MDB

Java Message Services

Message Driven Beans

(2)

Objectives

• Java Message Services

– Enterprise Message System – Message Oriented Middleware – JMS Definitions

– Message Domain Models – Implementation

– Development Process – Comparable

• Message Driven Beans

– Definition

– MDB Components – Life Cycle

– Implementation

– Development Process

(3)

Java Message Services

Message

• Is an alternative to remote method invocation

• Message (such as SMS or Email) is a data, which is used for communication.

• Message is used through a middle object (such as MOM or MQ) for sending and receiving the events and data between software component/ application.

– A middle object placed between the client and the server receives messages from message producers and broadcasts these messages to one or multiple message consumers

• Disadvantages: it reduces the performance as it increases the overhead of placing message middle object

(4)

Java Message Services

Enterprise Message System – EMS

• Provide facilities (synchronous/ asynchronous) for creating, sending, and receiving message.

– Asynchronous: The message producer can send a message, continue with other task, and later be notified of the response when the consumer completes the task of sending a message

• Application A communication Application B by sending a message via the MOM’s application programming interface.

Sender Receiver

Messages MOM

Message Oriented Middleware Or Message Queue

(5)

Java Message Services

Message Oriented Middleware – MOM

• Is an infrastructure that supports messaging

• Is a software which

– Enables asynchronous message exchange between system components

– Stores the message at a specified location specified by the sender and acknowledges immediately

• Contains terminologies

– Message producer – sender of the message

– Message consumer – retrieves the stored message – Destination – location where the messages are stored

• Apply to a distributed system for sending and receiving message between software components on network.

• Provide facilities for fault tolerance, load balancing, scalability, and transaction.

• Use formating message and network protocol in processing.

(6)

Java Message Services

Message Oriented Middleware – MOM

(7)

Java Message Services

Definition

• Is a messaging standard that is designed to eliminate the disadvantages of MOM based products

• Is an standard messaging API available with Java platform for different MOM based architectures

– The JMS API defines a common set of interfaces and associated semantics that allow creation of applications that use JMS to communicate with other applications.

• Is a Java-based messaging system that provides the facility of creating, sending, receiving, and reading messages to Java enterprise applications.

• Is an object in application server and uses message

• JMS consists of two parts

– Application Programming Interface (API) – Used to write code to send and receive messages

– Service Provider Interface (SPI) – Used to plug-in the JMS provider

(8)

Java Message Services

Definition

• The JMS API enables communication that is:

– Asynchronous

• JMS service can deliver messages to a client as they arrive.

• A client does not have to request for messages in order to receive them.

– Reliable

• Ensure that there is no duplicate delivery of messages and no message is missed

• Ensures one-time delivery, which means that the message will be delivered only once to the recipient

• Contains terminologies

– JMS clients are application using JMS

• A single JMS client can act as a producer and a consumer

– JMS providers are the messaging system that take care of message routing and delivery

– JMS application consists of many JMS Client and one JMS provider

(9)

Java Message Services

Architecture

Messages

Administered Objects

JMS Clients

JMS Provider JMS Application

Vendor who provides an implementation for JMS

specification

These are Java applications which are responsible for producing or consuming

messages from the JMS Provider Messages are objects that

contain the required data for communication between two

JMS Clients.

These are pre-configured JMS Objects created by an administrator for the use of clients

(10)

Java Message Services

Architecture

JMS Client (Java Application)

JMS API

SonicMQ IBM

MQSeries JBossMQ

Messaging Server

Messaging Server Messaging

Server

JMS provider Client tier Messages

JMS SPI

Plug-in

(11)

Java Message Services

Participants

• The administrative objects are bound to JNDI

namespaces using the administration tool provided by the application server.

• The different parts of JMS interact to form a connection so that messages can be passed between the clients.

• A JMS client looks up the administered objects in the JNDI namespace and then establishes a logical connection to the same objects using the JMS provider

lookup bind

Messaging System

/ JMS Provider

/ MOM

JNDI Namespace

Application Server Administrative Tool

Application Client

Connection Factory

Destination

(12)

Java Message Services

Domain Models

• The ways in which messages could be delivered to recipients (application, components, and users ...)

• There are 2 ways

– Point to Point (P2P)

– Publish / Subscribe (Pub/Sub)

(13)

Java Message Services

P2P Model

• Is build around the concept of

– Message queue: destination – use queues to receive messages from senders and̀ deliver message to receiver or destroy expired message (time out).

– Senders: send message to destination

– Receivers: receive the message from the queue and processes it (destination deliver messages to receivers)

• 1:1 Model.

• FIFO is applied.

• Acknowledge.

• Disadvantages: receiver is blocked until the message arrives.

• Advantages:

– High security.

– Receiver is not active when sender send message .

(14)

Java Message Services

P2P Model

Client1 Queue Consumer

sends

acknowledges consumes

Message

Message

Sender send

m1

m1 consumes

acknowledges

Receiver

Destination (Queue)

FIFO

m1 m2

m2 m3

m3 m4

m4

(15)

Java Message Services

Pub/Sub Model

• Is build around the concept of

– Topic: publish messages to destination. Destination retains message for only as long as it takes to distribute them to current (deliver message copies to) subscribers.

– Publisher: send message to Topic. It is event generator and create messages or events that are distributed to all the subscribers

– Subscriber: object to which destination deliver message. It is similar to listeners and register for particular event topic

• Is an implementation of distributed event-driven processing model

• 1:n Model (Acknowledge is optional) and a push-based model

• Topic is virtual channel for consumer receiving message.

• Message is received depend on the priority of message.

• There are 2 subscribers:

– Durable: receive messages even thought client is not active. The authentication is required.

– Non durable: Subscriber must be active in sending message process, otherwise message is lost.

• Disadvantages: low security

• Advantages: use in distributed system, multi-users

(16)

Java Message Services

Pub/Sub Model

Client1

Client 2 Topic

publishes

Delivers Subscribes

Message Message

Client 3

Delivers Subscribes

Message

Destination (Topic)

m4

m1

Sender publishes m1

delivers subscribes

Receiver

delivers subscribes

Receiver

m2 m1 m3

(17)

Java Message Services

In Action

Messaging Server 2

• Coordinate between P2P and Pub/Sub

• System is constructed into Message Channel

Messaging Server 1

Message

Channel App #

App 1 msg msg

msg

(18)

Java Message Services

Message Delivery

• The messaging models support

– Synchronous message delivery

• A subscriber or a receiver explicitly retrieves the message by calling the receive method.

• The receive method can keep the application in the waiting model until a message arrives or can time out if a message does not arrive within a specified period of time.

– Asynchronous message delivery

• A client can register a message listener with a consumer.

• A message listener is like an event listener which detects message delivery events. Whenever a message arrives, the JMS provider calls the listener’s onMessage() method which helps in delivering the message.

(19)

Programming Model

JNDI Namespace

Destination

(Queue/Topic) ConnectionFactory Destination

(Queue/Topic)

lookup lookup

lookupcreate

Administered object

Connection

create

Session

create

Message

MessageConsumer

receive / subscribe

create

MessageProducer

send / publish

create

Client

bindbind bind

connect

(20)

Java Message Services

Destinations

• A client who wishes to send or receive a message needs to be aware of the destination which has been configured by the administrator.

• The naming convention won’t be the same as in email addresses.

Ex: The name of the destination info@google.com could be

“jms/OrderQueue”.

• Are implemented as queue or topic in JBoss.

• Ex: Destinations are deployed on JBoss with JNDI “queue/testQueue”

and “topic/testTopic”

Context ctx = new InitialContext();

...

Queue queue = null;

queue = (Queue) ctx.lookup(“queue/testQueue”);

Context ctx = new InitialContext();

...

Topic topic = null;

topic = (Topic) ctx.lookup(“topic/testTopic”);

(21)

Connection Factories

• Similar to the concept of DataSource in JDBC

• In JMS also, an administrator would configure the Connection Factory on the server, so that any application which needs to send or receive message from the MOM can obtain a ready connection from the Connection Factory.

• 02 interface ConnectionFactory is supported

– QueueConnectionFactory – TopicConnectionFactory

InitialContext jndiContext=new InitialContext();

QueueConnectionFactory queueConnectionFactory = null;

queueConnectionFactory=(QueueConnectionFactory)jndiContext.

lookup("QueueConnectionFactory");

or

queueConnectionFactory=(QueueConnectionFactory)jndiContext.

lookup("ConnectionFactory");

InitialContext jndiContext=new InitialContext();

TopicConnectionFactory topicConnectionFactory = null;

topicConnectionFactory=(TopicConnectionFactory)jndiContext.

lookup(“TopicConnectionFactory");

or

topicConnectionFactory=(TopicConnectionFactory)jndiContext.

lookup("ConnectionFactory");

(22)

Java Message Services

Connections

• Is used to represent a virtual connection with JMS Provider

• Could be an open TCP/IP connection between the client and the provider.

• Is created from Connection Factory

• If connection has to be established for sending or receiving message from a queue, then QueueConnection interface is used. Otherwise, TopicConnection interface is used.

• Whenever an application completes, the close() method is called.

QueueConnection queueConnection=null;

...

queueConnection=queueConnectionFactory.createQueueConnection();

...

queueConnection.close();

TopicConnection topicConnection=null;

...

topicConnection=topicConnectionFactory.createTopicConnection();

...

topicConnection.close();

(23)

Java Message Services

Sessions

• A Session represents a single-threaded context for sending and receiving messages.

• Is created from Connections

• Provide a transactional context in which multiple message sent and received can be treated as a single atomic unit.

• The session automatically acknowledges message when the destinations have been received successfully

• There are QueueSession and TopicSession interfaces for queues and topics respectively.

QueueSession queueSession=null;

...

queueSession=queueConnection.createQueueSession(false, queueSession.AUTO_ACKNOWLEDGE);

TopicSession topicSession=null;

...

topicSession=topicConnection.createTopicSession(false, topicSession.AUTO_ACKNOWLEDGE);

(24)

Java Message Services

Message Producers

• Is created using the session object and is used for sending a message to the destination.

• If queues are used as destination, then QueueSender interface is used and if topics are being used, then TopicPublisher interface is used.

• The methods are used send(message) and publish(message)

Queue queue=null;

QueueSender queueSender=null;

...

queue=(Queue)jndiContext.lookup("queue/testQueue");

queueSender=queueSession.createSender(queue);

...

queueSender.send(message);

Topic topic=null;

TopicPublisher topicPublisher=null;

...

topic=(Topic)jndiContext.lookup(“topic/testTopic");

topicPublisher=topicSession.createPublisher(topic);

...

topicPublisher.publish(message);

(25)

Java Message Services

Message Consumers

• Is created using the session object and is used for receiving messages from the destination.

• There is a QueueReceiver and a TopicSubscriber interface for receiving messages from a queue or a topic respectively.

• Use receive() method.

Queue queue=null;

QueueReceiver queueReceiver=null;

...

queue=(Queue)jndiContext.lookup("queue/testQueue");

queueReceiver=queueSession.createReceiver(queue);

...

Message msg=queueReceiver.receive();

Topic topic=null;

TopicSubscriber topicSubscriber=null;

...

topic=(Topic)jndiContext.lookup(“topic/testTopic");

topicSubscriber=topicSession.createSubscriber(topic);

...

Message msg=topicSubscriber.receive();

(26)

Java Message Services

Message Listeners

• Provide an asynchronous way for handling incoming messages.

• Using the poll and the push mechanism which means that the listener automatically receive a notification for an incoming message

• setMessageListener() method is used to register a listener with the consumer classes.

• Define onMessage() method in interface MessageListener to receive asynchronous messages

QueueReceiver receiver = null;

receiver = session.createReceiver(queue);

...

MyMessageListener listener = new MyMessageListener();

receiver.setMessageListener(listener);

TopicSubscriber subscriber = null;

subsriber = session.createSubscriber(topic);

...

MyMessageListener listener = new MyMessageListener();

subscriber.setMessageListener(listener);

(27)

Java Message Services

JMS API Summary

Root Interface Point-to-Point Publisher/Subscriber ConnectionFactory QueueConnectionFactory TopicConnectionFactory

Connection QueueConnection TopicConnection

Destination Queue Topic

Session QueueSession TopicSession

MessageProducer QueueSender TopicPublisher MessageConsumer QueueReceiver, QueueBrowser TopicSubscriber

(28)

Java Message Services

Message Selectors

• Provide an expression which can be specified for filtering the messages received by the JMS provider.

• Disadvantages

– A message selector cannot filter messages based on the content of the message body

• Use Where clause in SQL 92 commands.

• Ex

– String messageSelector="itemName LIKE '%Book' and

price='45.0'";

(29)

Java Message Services

Message

• Data type is used to communication between software components/ applications.

• JMS messages have a specific format and have 3 parts

– Header

– Properties (optional)

– Body (optional)

(30)

Message Headers

• Contains a number of fields that both the JMS clients and providers can use to identify and to route messages

• A JMS message has a set of predefined keys and value pair data, which the client as well as the provider can use to identify and to relay message.

• The usage of SMTP as a protocol involves headers, as is also true for HTTP

• The value for the commonly known headers like TO, From, CC, BCC, Subject, is specified along with the actual message body.

• Every message sent has a unique identifier which is known as JMSMessageID header field.

Header Fields Description

JMS Destination Determine a destination store messages

JMSDeliveryMode Determine a mode delivered message to consumers JMSExpiration The life cycle of message on destination

JMSPriority Priority of message in deliver process.

JMSMessageID A unique identifier of Message JMSTimestamp The sending time of message

JMSCorrelationID A identifier message correlate with current message (Ex: message A is replied from message B) JMSReplyTo A responsing mode

JMSType A message structure.

JMSRedelivered Determine message delivered over once times

(31)

Java Message Services

Message Properties

• Optional

• The parameters required by a message are specified using message properties

• Provide compatibility with other messaging systems and also creating message selectors

• All message properties are pre-fixed with JMS

• Message properties include Name & Value

• Some predefined properties are included in the JMS API.

• All the header fields such as JMSMessageID and JMSDestination are instances of message properties

• Can use either predefined properties or user-defined properties in the JMS application

• Developer can define message properties using methods like setStringProperty(), setDoubleProperty(), and setShortProperty() of javax.jms.Message interface

(32)

Java Message Services

Message Body

• Optional

• Contain the actual content of the message

• The contents of the message in different formats

Types Descriptions

TextMessage

For sending data in form of a text. Ex

TextMessage message = session.createTextMessage();

message.setText("Hello");

MapMessage

Sending data in the form of key, value pairs. Storage Data is similar to ResultSet. Ex

MapMessage msg=null;

msg=topicSession.createMapMessage();

msg.setString("studentId", "987");

BytesMessage Sending binary data

StreamMessage Sending Java primitives as a stream of values ObjectMessage Sending a Serializable Java Object as a message

Message Sending a message with only JMS headers and properties with no body associated with it.

(33)

Java Message Services

Exception Handling

• The root class for JMS exceptions is javax.jms.JMSException

Exceptions Descriptions

InvalidSelectorException Is thrown when a JMS al attempts use a message selector with invalid syntax.

JMSSecurityException

Is thrown when a JMS provider does not recognize the client’s name/password or security restrictions prevent a method from completing.

ResourceAllocationException Is thrown when a provider is unable to allocate the resources required by a method.

MessageEOFException Is thrown when an unexpected end of stream is reached when a message of type StreamMessage or BytesMessage is being read.

MessageFormatException

Is thrown when a JMS client attempts to use a data type not supported by a message or attempts to read data of wrong type in a message.

MessageNotReadableException Is thrown when a JMS client attempts to read a write-only message.

MessageNotWriteableException Is thrown when a JMS client attempts to write a read-only message.

TransactionInProgressException Is thrown when an operation is invalid because a transaction is in progress.

TransactionRolledBackException Is thrown when the current transaction rolls back.

(34)

Java Message Services

Durable Subscriptions

• Whenever a topic is configured on a JMS server, all the messages published to the topic would be retained only for the duration of availability of the subscriber.

• A durable subscription can have only active subscriber at a time

• The createDurableSubcriber() method in TopicSession interface is used to created a durable subscriber

• A JMS provider may provide a capability to configure a

durable subscription as an administered object.

(35)

Java Message Services

Transactions

• In JMS transaction, if a single messages process fails, there can be a need to abort the complete process.

• The interface javax.jms.Session defines commit() and rollback() method to control transaction boundaries.

• The createQueueSession() or createTopicSession() method check whether all the messages which will be sent or received will be transacted or not.

QueueSession queueSession=null;

...

queueSession=queueConnection.createQueueSession(false, queueSession.AUTO_ACKNOWLEDGE);

A boolean value of true means that all the messages will be sent only if the commit() method will be called.

(36)

Java Message Services

Transactions

• Sender

– Till the commit() method is not called, all the messages are not immediately sent to destination, but are buffered in an internal memory buffer. (means that the message is sent to destination when session invokes commit() method.)

– JMS supports multi – transaction.

– As soon as the commit() or rollback() invocation completes, it signifies the end of one transaction.

• Receiver:

– The commit method is set default in delivering message.

– If the receiver needs to rollback the transaction, then all the messages that were received within the current transaction will be thrown back into the destination and JMSRedelivered property is set for processing message.

• The grouping of sending and receiving multiple messages within a JMS Session using the methods provided by JMS API is called local transactions.

• Whenever a JMS session is a part of an existing transaction which already has been started, the parameter value is passed as false.

(37)

Java Message Services

Transactions

Client

RDBMS Application Server

API

Trans- action

Java

Mainframe / ERP

MOM / MQ JMS

JDBC

JCA Servlets

/ JSP

EJB

•J2EE/JavaEE includes support for JTA which allows developers control on the transaction boundaries within the code.

• javax.transaction.UserTransaction interface is used to manage transaction

(38)

Java Message Services

Message Acknowledged

• Until a JMS message has been acknowledged, it is not considered to be successfully consumed.

• For the successful comsumption of a message, a client need to

• In transacted session, acknowledge happen automatically when a transaction is commited.

• In non-transacted session, message acknowledge depend on the value of the second parameter pass to the createQueueSession() or createTopicSession() method.

(39)

Java Message Services

Message Acknowledged Modes

• AUTO_ACKNOWLEDGE

– JMS session is responsible for automatically acknowledging the message received

– Acknowledge synchronous after the receive() method call or asynchronous after the onMessagẹ() callback method call.

• CLIENT_ACKNOWLEDGE

– JMS Client is responsible for manually acknowledging the message using the acknowledge() method after sucessfully consuming the message.

– Acknowleding even a single message in the session causes all the messages to be acknowledged automatically.

• DUPS_OK_ACKNOWLEDGE:

– The JMS session can lazily acknowledge for message after they are consumed. (The consumer can tolerate duplicate message)

(40)

Java Message Services

Session Bean & JMS

• Session Beans as Message Producer

– A session bean can send messages using an object of

• javax.jms.MessageProducer interface, which is the parent interface for all message producers

• javax.jms.TopicPublisher objects

• javax.jms.QueueSender objects.

• Session Beans as Message Receiver

– A session can also receive messages or acts as a message consumer.

– However, a session bean cannot directly receive a message on its own. To receive a message, the message receiving code is added to a business method, which is called by a client to start receiving the message.

– To create a session bean message consumer, needing to create a business method that declares an object of QueueReceiver or TopicSubscriber interfaces.

– Then, call the receive() method on either of these objects.

• Limitations

– The session bean consumer can only work in synchronous mode

– The bean reaches the message receiving stage, it stops execution and starts waiting for a message to arrive

– Avoid using a session bean in a production environment, where a bottleneck like this would have an adverse effect on the overall working of the application

(41)

Java Message Services

Entity Bean & JMS

• Messaging capabilities of an entity bean is very similar to session beans.

• Entity beans can work as both message consumer and synchronous message producer.

• Entity beans can send messages using javax.jms.MessageProducer, javax.jms.TopicPublisher, or javax.jms.QueueSender objects.

• Entity beans can receives messages using the synchronous receive() method of the javax.jms.MessageConsumer interface.

• The receive() method can be specified the timeout value or use receiveNoWait() method that receives the available message and does not wait.

• Limitations

– The entity bean consumers are not recommended in a J2EE/JavaEE application because of its blocking nature

– Should instead opt for a message-driven bean if wanting a bean consumes a message

(42)

Java Message Services

MDB & JMS

• MDB are designed to be message consumers in a J2EE application.

• To receive messages, a MDB must implement a Message Listener with the onMessage() method (callback method) contains the code that are executed when a message arrives.

• The MDB can send messages. Even though its strength lies in being a consumer, it can also send messages to other messaging components.

• Messages can be sent from a MDB by declaring objects of javax.jms.MessageProducer, javax.jms.TopicPublisher, or javax.jms.QueueSender interfaces, and then calling the send() method

• Limitations

– MDB works only in asynchronous mode

– MDB cannot be invoked without a JMS message, they are more suited as message consumers than as message producers

– MDB can send messages, but only after being invoked by an incoming message – MDB are currently designed to map to only a single queue or topic.

– MDB can only listen for messages on that destination only

(43)

Java Message Services

Implementation in JBoss

• Queue and Topic connection factory

– JNDI name is ConnectionFactory (JBoss 5.1.0 GA)

– Is defined in connection-factories-service.xml file at JBOSS_HOME\server\default\deploy\messaging\

(44)

Java Message Services

Implementation in JBoss

• JMS domain in JBoss is defined in destinations-service.xml file located at JBOSS_HOME/server/default/deploy/jms

– Some destination are not configured in JBoss 5.x

– The destinations are set default: Dead Letter Queue and Default Expiry Queue

(45)

Java Message Services

Implementation in JBoss

• The mechanism and roles of JMS in JBoss is

defined in the hsqldb-persistence-service.xml file located at

JBOSS_HOME/server/default/deploy/jms

• The JMS library files: jboss-javaee.jar, jbossall- client.jar, concurrent.jar, jboss-ejb3-common- client.jar, jboss-messaging-client.jar, jboss- system-client.jar, log4j.jar, jnp-client.jar (located at JBOSS_HOME\client)

• Using the appropriate Exception in coding

(46)

Java Message Services

Configure the Destination in JBoss 5.x.x

• Configure the Queue and Topic destination same as the JBoss 5.x

– Open the destinations-service.xml in

JBOSS_HOME\server\default\deploy\messaging\

– Type the configuration as

(47)

Java Message Services

Steps in Implementation

(48)

Java Message Services

Steps in Implementation

• Step 1: Get ConnectionFactory

• Step 2: Look up Destinations

• Step 3: Create connection from Connection Factory

• Step 4: Create Session from Connection

• Step 5: Create Sender or Receiver – register the listener for receiver (asynchronuous)

• Step 6: Create Message

• Step 7: Execute sending or receiving Message (processing and consuming)

• Step 8: Close Connection

(49)

Java Message Services

Development in Process

• Requirement: JBoss 5.1.0 GA Application Server must be running

• Step 1: Creating Application using JMS API to send/publish or receive/subscriber message from/to JMS Destination

• Step 2: Creating references to Application Server.

• Step 3: Running the client to test the JMS client

(50)

Java Message Services

P2P Sender

(51)

Java Message Services

P2P Receiver

(52)

Java Message Services

P2P Executing

• Case 1

– Run Sender to send message to Queue.

– Then, run Receiver to receive message (→receive sent message)

– Then, run Receiver again. Pay attention the receiver in this running (→ receiver waiting to receive because the Destination has no message)

• Case 2

– Run Receiver

– Then run Sender (→ receiver receive message

immediately)

(53)

Java Message Services

P2P Executing

(54)

Java Message Services

Publisher

(55)

Java Message Services

Subscriber

(56)

Java Message Services

Subscriber

(57)

Java Message Services

Pub/Sub Executing

• Case 1

– Run Publisher to send message to Topic.

– Then, run Subscriber (→ cannot receive message because the listener is not activated)

• Case 2

– Run Subscriber

– Then run Publisher (→ receive sent message)

(58)

Java Message Services

Pub/Sub Executing

(59)

Java Message Services

Durable Subscriber

(60)

Java Message Services

Pub/Durable Sub Executing

• Run Publisher to send message to Topic.

• Then, run Durable Subscriber (→ Receive message from destination because the Durable Subscriber with authentication allows to do this without the Listener not to be activated)

(61)

Java Message Services

Sender Transaction – Sender

(62)

Java Message Services

Sender Transaction Executing

• Case 1

– Run sender with the commit() statement in the last

– Run receiver (→ get two message from the destination)

• Case 2

– Run sender without both the rollback() and the commit() statement

– Run receiver (→ not get message because the transaction is not commit, the message is on the buffer)

– Run new sender with the commit() statement (new transaction) in the last (→

get the message, means that the transaction can be created new one without the current transaction has been finished yet)

• Case 3

– Run sender with the rollback() statement at the first message and the commit in the second message

– Run receiver (→ receive only message 2)

(63)

Java Message Services

Sender Transaction – Receiver

(64)

Java Message Services

Sender – Receiver Transaction

(65)

Java Message Services

Sender – Receiver Transaction

(66)

Java Message Services

Receiver Transaction Executing

• Case 1

– Run sender

– Run receiver without the commit() and the rollback() statement (→ get two message from the destination because the default of destination is always commit)

• Case 2

– Run sender

– Run receiver with the rollback() statement at the receive first message and without if(!message.getJMSRedelivered()) statement (→ get the message in order 1st – 1st – 2nd , the 1st message redeliver to destination at the its position before delivering)

• Case 3

– Run sender

– Run receiver with the rollback() statement at the receive first message and if(!message.getJMSRedelivered()) statement (→ get the message in order 1st – 2nd because the JMSRedelivered supports to reject the message receive twice)

(67)

Message Driven Beans

Definition

• Introduced in EJB 2.0

• A server-side EJB component which is invoked by the container

– Similar to other enterprise beans, which deployed on an EJB container before they can be used.

– All the container services such as resource handling, transaction management, and security are also available to the MDB.

• Used for processing asynchronous messages using JMS

– Normally acts as a JMS message listener, which is similar to an event listener except that it receives JMS messages instead of events.

– The messages can be sent by any J2EE component such as an application client, another enterprise bean, or a web component, or by a JMS application or system that does not use J2EE technology.

• MDB can process either JMS messages or other kinds of messages.

• Does not have a remote or local business interface

– A client cannot access the Message-driven bean through business interface

(68)

Message Driven Beans

JMS & MDB

• JMS has been part of J2EE since 1999, MDB were introduced in 2001 with EJB 2.0.

• Before MDB, the JMS message consumers were built as simple java program.

• MDB allows JMS applications to receive messages asynchronously (the sender is independent of the receiver receiving and processing the messages).

• Building these message consumers was difficult task.

• These message consumers had to include code for handling issues, such as scalability, resource management, transactions, and security in a multithreaded environments.

• If the message load grew, multiple consumers had to be

created so that the messages were not lost. Then, an

additional program had to be written to manage multiple

consumers.

(69)

Message Driven Beans

Definition

• Characteristics

– Execute upon receipt of a single client message.

– Invoked asynchronously.

– Relatively short-lived.

– Don’t represent directly shared data in the database, but they can access and update data.

– Can be transaction-aware.

– Absence of remote or local business interface – Are similar to the stateless session bean

– Support for generic listener method for message delivery – Absence of return types for Listener methods

– Are Stateless

– Are single-threaded

– Uses simple Messaging code

(70)

Message Driven Beans

Components

• MDB Components

– MDB bean class

• Must not be declared as final or abstract

• Must not implement the finalize method

• Must implement the message listener interface either directly or indirectly

– The javax.jms.MessageListener interface

• Must be declared as public

• Must have a default constructor without any arguments

• Must implement the methods defined in the message listener interface

– onMessage(javax.jms.Message): implement the main business-logic and bean executes upon receipt of a message

• Cannot be a subclass of another Message-driven bean class

• Cannot define a final method

• MDB connects JMS destination, which is middle object, to

store Message

(71)

Message Driven Beans

Components

(72)

Message Driven Beans

Life Cycle

• There are 2 states: Does not Exist and Method-Ready

– In Does not Exist state, the bean is not instantiated or not exist in the memory

– When the EJB server starts, a number of MDB instances are created and they enter into Method-Ready state from Does not Exist (after that, the onMessage is invoked when the message is received)

• First, new bean instance is created by invoking the Class.newInstance

• Second, any dependency injection that exists is performed

• Finally, the EJB container invokes the PostConstruct life cycle callback method if it exists

– When the server shuts down, the container can remove the bean instance from the pool and destroy it. Before the destroy action is executed, the @PreDestroy method is invoked

(73)

Message Driven Beans

Development Process

• Requirement: JBoss 5.1.0 GA Application Server

• Step 1: Creating a new EJB Module project

• Step 2: Creating the new MDB, then building/

Modifying the business/callback methods on Beans.

• Step 3: Mapping the JNDI to beans

• Step 4: Building the project to jar file

• Step 5: Deploying the project on Application server

• Step 6: Creating the client application to consume

• Step 7: Running the client to test the MDB

(74)

Message Driven Beans

Creating MDB

• Click Next Button

(75)

Message Driven Beans

Creating MDB

Fill your bean name

Choose the appropriate destination

Click Ok Button

Click Finish Button

(76)

Message Driven Beans

Creating MDB

Client

Public Message

Topic deliver Message

MDB onMessage()

(77)

Message Driven Beans

Creating MDB

(78)

Message Driven Beans

Mapping

(79)

Message Driven Beans

Consuming

(80)

Message Driven Beans

Building, Deploying, and Testing

• Building the jar file and deploying to Application Server → Application Server do not present the binding with the MDB Bean because we mapped to the destination JNDI

• Running the application client, the message is consumed on the Application Server

(81)

Message Driven Beans

Creating MDB with Customized Destination

• Creating MDB with supporting chatting between many clients

• Creating the GUI uses Swing Component that is installed in each client

• The proposal GUI is seen as

(82)

Message Driven Beans

Creating MDB with Customized Destination

• Creating EJB Module Project is named EJB3MDBChat

• Creating Message Driven Bean is named ChatBean

(83)

Message Driven Beans

Creating MDB with Customized Destination

• Click Add to create the destination naming service (e.g Chat) with Topic Type

(84)

Message Driven Beans

Creating MDB with Customized Destination

• Customizing MDB Code as following

(85)

Message Driven Beans

Creating MDB with Customized Destination

• Customizing MDB Code as following

(86)

Message Driven Beans

Creating MDB with Customized Destination

• Customizing MDB Code as following

(87)

Message Driven Beans

Creating MDB with Customized Destination

• Customize the jboss.xml file

(88)

Message Driven Beans

Creating MDB with Customized Destination

• Deploy

(89)

Message Driven Beans

Creating MDB with Customized Destination

• Creating Java Application Project is named MDBChatApp

• Creating JFrame Form from Swing GUI Forms as following

(90)

Message Driven Beans

Creating MDB with Customized Destination

(91)

Message Driven Beans

Creating MDB with Customized Destination

• Action perform of Connect button

(92)

Message Driven Beans

Creating MDB with Customized Destination

(93)

Message Driven Beans

Creating MDB with Customized Destination

• Create the run method that create many instance for client

(94)

Message Driven Beans

Creating MDB with Customized Destination

• Build, Run the Application with 2 instance

(95)

Message Driven Beans

Creating MDB with Customized Destination

(96)

Summary

• Java Message Services

• Message Driven Beans

Q&A

(97)

Next Day

• Practical Test

– Servlet, JSP combines EJB in building web application – Must used the JBoss Server

Good luck to you 

References

Related documents

Dans le cadre de cette démarche, la Ville a mis sur pied un comité des élus auquel participe M me Andrée Hénault, conseiller de ville pour l’arrondissement d’Anjou, et dont

A study on measurement and modelling of BitTorrent messages for the link layer traces of measurement 13 is reported in [3]. For the upstream leech phase request rate models

These three figures are all from Gerald Gish, Fu Chen, et al., and one table I use is from the general lecture you give to the students for experiments in September. Here I attach

Regarding the questions whether the respondents experience advertising as something forced or  disturbing online, one can examine that the respondents do experience advertising

resurser till ett program med processer, och semaforer för att skydda dessa resurser samt noll eller flera händelsevariabler för att kontrollera accessen av resurser i

In this three-sections lecture cavity method is introduced as heuristic framework from a Physics perspective to solve probabilistic graphical models and it is presented both at

The body, being in free text form, is much harder to deal with since exact string matching may be possible but since different words may be used to describe different phenomena

In our case, we have two types of messages and choose to divide the systems fixed rate R b into two channels with the split ratio γ ⊂ [0, 1]. For each channel, there is a