J2EE JMS

  • Upload
    dsuntew

  • View
    228

  • Download
    0

Embed Size (px)

Citation preview

  • 8/8/2019 J2EE JMS

    1/120

    Java Messaging Service(JMS)

  • 8/8/2019 J2EE JMS

    2/120

    Agenda

    What is Messaging? Messaging models, Reliability, Transaction,

    Distributed messaging, Security

    Why Messaging?

    What is JMS?

    Architecture of JMS

    JMS Programming APIs

  • 8/8/2019 J2EE JMS

    3/120

    What is Messaging?

  • 8/8/2019 J2EE JMS

    4/120

    Messaging System Concepts De-coupled (Loosely-coupled) communication

    Asynchronous communication

    Messages are the means of communicationbetween applications.

    Underlying messaging software provides

    necessary support MOM (Message Oriented Middleware), Messaging

    system, Messaging server, Messaging provider,

    JMS provider: they all mean this underlying

    messaging software

  • 8/8/2019 J2EE JMS

    5/120

    Messaging System Features

    Support of two messaging models Point-to-point

    Publish/Subscribe

    Reliability

    Transactional operations Distributed messaging

    Security

  • 8/8/2019 J2EE JMS

    6/120

    Additional Features

    Some Messaging System vendorssupport

    Guaranteed real-time delivery Secure transactions

    Auditing

    Metering Load balancing

  • 8/8/2019 J2EE JMS

    7/120

    Messaging Models

  • 8/8/2019 J2EE JMS

    8/120

    Messaging Models

    Point to Point A message is consumed by a single

    consumer

    Publish/Subscribe A message is consumed by multiple

    consumers

  • 8/8/2019 J2EE JMS

    9/120

    Point-to-Point

    A message is consumed by a singleconsumer

    There could be multiple senders

    "Destination" of a message is a namedqueue

    First in, first out (at the same priority level)

    Senders (producers) sends a message to anamed queue (with a priority level)

    Receiver (consumer) extracts a message

    from the queue

  • 8/8/2019 J2EE JMS

    10/120

    Point-to-Point

    QueueClient

    Senders SendsConsumes

    Acknowledges

    ClientReceiver

    Receives messages on

    the queue

    Posts messages to the

    queue

  • 8/8/2019 J2EE JMS

    11/120

    When to use Point-to-Point?

    Use it when every message you sendmust be processed successfully by

    one consumer

  • 8/8/2019 J2EE JMS

    12/120

    Publish/Subscribe (Pub/Sub)

    A message is consumed by multipleconsumers

    "Destination" of a message is a namedtopic not a queue

    Producers publish to topic

    Consumers subscribe to topic

  • 8/8/2019 J2EE JMS

    13/120

    Publish-and-Subscribe

    ClientSender Sends

    Consumes

    Acknowledges

    ClientReceiver

    ClientPublishe

    r

    Publishes Topic

    Clientsubscriber

    Clientsubscriber

    ClientPublishe

    rTopic

    Clientsubscriber

    Clientsubscriber

    Publishes

    Subject ofcommunication

    Available to registeredparticipants

    Posts messages to thetopic

    Receives messages

    on the topic

  • 8/8/2019 J2EE JMS

    14/120

    When to use Pub/Sub?

    Use it when a message you sendneed to be processed by multiple

    consumers Example: HR application

    Create new hire topic

    Many applications (facilities, payroll, etc.)subscribe new hire topic

  • 8/8/2019 J2EE JMS

    15/120

    Reliability

  • 8/8/2019 J2EE JMS

    16/120

    Reliability

    Some guarantee of delivery of a message

    Different degree of reliability is possible

    Sender can specify different level of reliability Higher reliability typically means less throughput

    Typically uses persistent storage forpreserving messages

  • 8/8/2019 J2EE JMS

    17/120

    TransactionalOperations

  • 8/8/2019 J2EE JMS

    18/120

    Transactional Operations

    Transactional production Sender groups a series of messages into a

    transaction

    Either all messages are enqueuedsuccessfully or none are

    Transactional consumption

    Consumer retrieves a group of messages asa transaction

    Unless all messages are retrievedsuccessfully, the messages remain in a

    queue or topic

  • 8/8/2019 J2EE JMS

    19/120

    Transactional Scope

    Client-to-Messaging system scope Transaction encompasses the interaction

    between each messaging client(applications) and the messaging system

    JMS supports this

    Client-to-Client scope

    Transaction encompasses both clients JMS does not support this

  • 8/8/2019 J2EE JMS

    20/120

    Client-to-Messaging System

    Transactional Scope

    Application 1 Queue Application 2

    Messaging system

    source: Applied Enterprise

  • 8/8/2019 J2EE JMS

    21/120

    Client-to-Client

    Transactional Scope

    Application 1 Queue Application 2

    Messaging system

    source: Applied EnterpriseJavaBeans[1]

  • 8/8/2019 J2EE JMS

    22/120

    DistributedMessaging

  • 8/8/2019 J2EE JMS

    23/120

    Distributed Messaging

    Enterprise messaging systems mightprovide an infrastructure in which

    messages are being forwardedbetween servers called message channel

  • 8/8/2019 J2EE JMS

    24/120

    Distributed Messaging

    Application 1

    Application 2

    messa

    ge

    Queue

    Queue

    Messaging server

    2

    Messaging server 1

    Message channel

    messa

    ge

    source: Applied Enterprise JavaBeans[1]

  • 8/8/2019 J2EE JMS

    25/120

  • 8/8/2019 J2EE JMS

    26/120

    Security Issues

    Authentication Messaging systems typically require clients to

    present signed certificates

    Confidentiality of messages Messaging system typically provide

    encryption

    Data integrity of messages Messaging system typically provide data

    integrity through message digest

    Security is currently handled in vendor-

    specific way

  • 8/8/2019 J2EE JMS

    27/120

    Why Messaging?

  • 8/8/2019 J2EE JMS

    28/120

    Why Messaging?

    Platform independence

    Network location independence

    Works well in heterogeneous environments

  • 8/8/2019 J2EE JMS

    29/120

    Why Messaging?

    Anonymity Whodoesnt matter

    Wheredoesnt matter Whendoesnt matter

    Contrast with RPC-based systems CORBA

    RMI

  • 8/8/2019 J2EE JMS

    30/120

  • 8/8/2019 J2EE JMS

    31/120

    Why Messaging?

    Robustness Receivers can fail.

    Senders can fail. Network can fail.

    Messaging System continues to function.

  • 8/8/2019 J2EE JMS

    32/120

    Example MessagingApplications

  • 8/8/2019 J2EE JMS

    33/120

    Messaging Applications

    Credit card transactions

    Weather reporting

    Workflow Network management

    Supply chain management

    Customer care

    Communications (Voice Over IP,Paging Systems, etc.)

    Many more

  • 8/8/2019 J2EE JMS

    34/120

    What is JMS?

  • 8/8/2019 J2EE JMS

    35/120

    What is JMS?

    JMS is a set of Java interfaces and associatedsemantics (APIs) that define how a JMS clientaccesses the facilities of a messaging system

    Supports message production, distribution,delivery

    Supported message delivery semantics

    Synchronous or Asynchronous transacted

    Guaranteed

    Durable

  • 8/8/2019 J2EE JMS

    36/120

    What is JMS? (Continued)

    Supports existing messaging models Point-to-Point (reliable queue)

    Publish/Subscribe

    Message selectors (on the receiver side)

    5 Message types

  • 8/8/2019 J2EE JMS

    37/120

    JMS is an API

    Java Application

    JMS API

    JMS

    Provider

    IBMMQSeries

    JMS

    Provider

    ProgressSonicMq

    JMS

    Provider

    Fiorano

    JMS

    Provider

    JMS

    Provider

    BEA SUN MQ

  • 8/8/2019 J2EE JMS

    38/120

    38

    JMS and J2EE

    Allows Java Developers to accessthe power of messaging systems

    Part of the J2EE Enterprise Suite

    JMS

  • 8/8/2019 J2EE JMS

    39/120

    JMS Design Goals

    Consistency with existing APIs

    Independence from Messaging

    system provider Minimal effort on part of Messaging

    system provider

    Provide most of the functionalityof common messaging systems

    Leverage Java technology

  • 8/8/2019 J2EE JMS

    40/120

    Architecture ofa JMS Application

  • 8/8/2019 J2EE JMS

    41/120

  • 8/8/2019 J2EE JMS

    42/120

  • 8/8/2019 J2EE JMS

    43/120

    JMS Terminology

    Domain (Messaging modes) point-to-point, publish/subscribe

    Session Connection

    Destination

    Produce, send, publish Consume, receive, subscribe

  • 8/8/2019 J2EE JMS

    44/120

    JMS Domains(Messaging Models)

  • 8/8/2019 J2EE JMS

    45/120

  • 8/8/2019 J2EE JMS

    46/120

    JMS Pub/Sub Non-durable vs.

    JMS Pub/Sub Durable Non-durable

    Messages are available only during the time

    for which the subscriber is active If subscriber is not active (not connected), it

    will miss any messages supplied in itsabsence

    Durable Messages are retained on behalf of

    subscribers that are not available at the timethe message was produced

  • 8/8/2019 J2EE JMS

    47/120

    JMS Messages

  • 8/8/2019 J2EE JMS

    48/120

    Messages

    Messages are the means ofcommunication between messaging

    applications Actual on-the-wire Message formats vary

    widely among messaging systems A messaging system can interoperate with only

    with the same messaging system

  • 8/8/2019 J2EE JMS

    49/120

    Message Java Interface

    JMS provides a unified and abstractmessage model via this interface

    Actual object implementation of thisinterface is provider specific

  • 8/8/2019 J2EE JMS

    50/120

  • 8/8/2019 J2EE JMS

    51/120

    Message Header

    Used for message identification androuting

    Includes Destination

    Also includes other data: delivery mode (persistent, nonpersistent)

    message ID

    timestamp priority

    ReplyTo

  • 8/8/2019 J2EE JMS

    52/120

    Message Header Fields

    JMSDestination

    JMSDeliveryMode

    persistent or nonpersistent

    JMSMessageID

    JMSTimeStamp

    JMSRedelivered JMSExpiration

  • 8/8/2019 J2EE JMS

    53/120

  • 8/8/2019 J2EE JMS

    54/120

  • 8/8/2019 J2EE JMS

    55/120

    Message Body

    Holds content of message

    Several types supported

    Each type defined by a messageinterface: StreamMessage

    MapMessage

    TextMessage

    ObjectMessage

    BytesMessage

  • 8/8/2019 J2EE JMS

    56/120

    Message Body Interfaces

    StreamMessage: Contains Java primitive values

    Read sequentially

    MapMessage: Holds name/value pairs

    Read sequentially or by name

    BytesMessage Uninterpreted bytes

    Used to match an existingmessage format

  • 8/8/2019 J2EE JMS

    57/120

    Example:

    Creating Text Message To create a simple TextMessage:

    TextMessage message =session.createTextMessage();

    message.setText("greetings");

  • 8/8/2019 J2EE JMS

    58/120

    Example:

    Creating Object Message To create a simple ObjectMessage:

    ObjectMessage message =

    session.createObjectMessage();

    message.setObject(myObject);

    NOTE: myObjectmust implement

    java.io.Serializable

    http://java.io.serializable/http://java.io.serializable/http://java.io.serializable/
  • 8/8/2019 J2EE JMS

    59/120

    JMS ProgrammingAPIs

  • 8/8/2019 J2EE JMS

    60/120

  • 8/8/2019 J2EE JMS

    61/120

  • 8/8/2019 J2EE JMS

    62/120

  • 8/8/2019 J2EE JMS

    63/120

  • 8/8/2019 J2EE JMS

    64/120

    Connection Java Interface

    An abstraction that represents a singlecommunication channel to JMS provider

    Created from a ConnectionFactoryobject

    A connection should be closed when theprogram is done using it.

  • 8/8/2019 J2EE JMS

    65/120

    Connection Java Interface

  • 8/8/2019 J2EE JMS

    66/120

    Session Java Interface

    Created from a Connection object

    Once connected to the provider via aConnection, all work occurs in thecontext of a Session

    A session is single threaded, whichmeans that any message sending and

    receiving happens in a serial order, oneafter the other

    Sessions also provide a transactional

    context

  • 8/8/2019 J2EE JMS

    67/120

    Session Java Interface

  • 8/8/2019 J2EE JMS

    68/120

  • 8/8/2019 J2EE JMS

    69/120

    MessageProducer JavaInterface

  • 8/8/2019 J2EE JMS

    70/120

    MessageConsumer JavaInterface Clients which want to receive messagescreate MessageConsumer object viaSession object

    MessageConsumer object is attached toa Destination object

    Client can receive messages in two

    different modes Blocking

    Non-blocking

  • 8/8/2019 J2EE JMS

    71/120

    Receiving Messages in

    Blocking mode Client calls receive() method ofMessageConsumer object

    Client blocks until a message is available

  • 8/8/2019 J2EE JMS

    72/120

    Receiving Messages in Non-

    blocking mode Client registers a MessageListenerobject

    Client does not block When a message is available, JMSprovider then calls onMessage() method

    of the MessageListenerobject

  • 8/8/2019 J2EE JMS

    73/120

    MessageConsumer JavaInterface

  • 8/8/2019 J2EE JMS

    74/120

    JMS APIs

  • 8/8/2019 J2EE JMS

    75/120

    JMS APIs

  • 8/8/2019 J2EE JMS

    76/120

  • 8/8/2019 J2EE JMS

    77/120

  • 8/8/2019 J2EE JMS

    78/120

    78

    (1) Locate ConnectionFactory andDestination objects via JNDI

    // Get JNDI InitialContext objectContext jndiContext = new InitialContext();

    // Locate ConnectionFactory object via JNDITopicConnectionFactory factory =

    (TopicConnectionFactory) jndiContext.lookup(

    "MyTopicConnectionFactory");

    // Locate Destination object (Topic or Queue)

    // through JNDI

    Topic weatherTopic =

    (Topic) jndiContext.lookup("WeatherData");

  • 8/8/2019 J2EE JMS

    79/120

    79

    (2) Create Connection Object

    // Create a Connection object from// ConnectionFactory object

    TopicConnection topicConnection =

    factory.createTopicConnection();

  • 8/8/2019 J2EE JMS

    80/120

  • 8/8/2019 J2EE JMS

    81/120

    81

    4) Create Message Producer

    // Create MessageProducer from Session object// TopicPublisher for Pub/Sub

    // QueueSender for Point-to-Point

    TopicPublisher publisher =session.createPublisher(weatherTopic);

  • 8/8/2019 J2EE JMS

    82/120

    82

    (6) Start Connection

    // Until Connection gets started, message flow// is inhibited: Connection must be started before

    // messages will be transmitted.topicConnection.start();

  • 8/8/2019 J2EE JMS

    83/120

    83

    (6) Publish a Message

    // Create a MessageTextMessage message =

    session.createMessage();message.setText("text:35 degrees");

    // Publish the message

    publisher.publish(message);

  • 8/8/2019 J2EE JMS

    84/120

  • 8/8/2019 J2EE JMS

    85/120

    Steps for Building a JMS Receiver

    Application (non-blocking mode)1.Get ConnectionFactory and Destination

    object (Topic or Queue) through JNDI

    2.Create a Connection3.Create a Session to send/receive messages

    4.Create a MessageConsumer (TopicSubscriberor QueueReceiver)

    5.Register MessageListener for non-blockingmode

    6.Start Connection

    7.Close Session and Connection

  • 8/8/2019 J2EE JMS

    86/120

  • 8/8/2019 J2EE JMS

    87/120

    87

    5) Register MessageListener

    object for non-blocking mode// Create MessageListener objectWeatherListener myListener

    = new WeatherListener();

    // Register MessageListener with// TopicSubscriber objectsubscriber.setMessageListener(myListener);

  • 8/8/2019 J2EE JMS

    88/120

    Steps for Writingblocking mode JMSReceiver Application

  • 8/8/2019 J2EE JMS

    89/120

    Steps for Building a JMS Receiver

    Application (non-blocking mode)1.Get ConnectionFactory and Destination

    object (Topic or Queue) through JNDI

    2.Create a Connection3.Create a Session to send/receive

    messages

    4.Create a MessageConsumer5.Start Connection

    6.Receive message

    7 Close Session and Connection

  • 8/8/2019 J2EE JMS

    90/120

    How to Build RobustJMS Applications

  • 8/8/2019 J2EE JMS

    91/120

    Most Reliable Way

    The most reliable way to produce amessage is to send a PERSISTENTmessage within a transaction.

    The most reliable way to consume amessage is to do so within atransaction, either from a queue or

    from a durable subscription to a topic.

  • 8/8/2019 J2EE JMS

    92/120

    Basic Reliability Mechanisms

    Controlling message acknowledgment

    Specifying message persistence

    Setting message priority levels Allowing messages to expire

    Creating temporary destinations

    Advanced JMS Reliability

  • 8/8/2019 J2EE JMS

    93/120

    Advanced JMS ReliabilityMechanisms

    Creating durable subscriptions

    Using local transactions

  • 8/8/2019 J2EE JMS

    94/120

    Controlling MessageAcknowledgment

    Phases of Message

  • 8/8/2019 J2EE JMS

    95/120

    Phases of MessageConsumption

    The client receives the message

    The client processes the message

    The message is acknowledged Acknowledgment is initiated either by the

    JMS provider or by the client, dependingon the session acknowledgment mode

    Transaction And

  • 8/8/2019 J2EE JMS

    96/120

    Transaction AndAcknowledgment

    In transacted sessions Acknowledgment happens automatically

    when a transaction is committed

    If a transaction is rolled back, all consumedmessages are redelivered

    In nontransacted sessions

    When and how a message is acknowledgeddepend on the value specified (see nextslide) as the second argument of thecreateSession method

  • 8/8/2019 J2EE JMS

    97/120

    Acknowledgment Types

    Auto acknowledgment (AUTO_ACKNOWLEDGE)

    Message is considered acknowledged when successfulreturn on MessageConsumer.receive() orMessageListener.onMessage()

    Client acknowledgment(CLIENT_ACKKNOWLEDGE)

    Client must call acknowledge() method of Message

    object Lazy acknowledgment

    (DUPS_OK_ACKNOWLEDGE)

    Messaging system acknowledges messages as soon

    as they are available for consumers

    H A k l d t T i

  • 8/8/2019 J2EE JMS

    98/120

    How Acknowledgment Type is

    set in JMS An acknowledge type is set when

    Session is created by setting appropriate

    flag QueueConnection.createQueueSession(..,)

    TopicConnection.createTopicSession(.., )

    ExampleTopicSession session =

    topicConnection.createTopicSession (false,Session.CLIENT_ACKNOWLEDGE);

  • 8/8/2019 J2EE JMS

    99/120

    Specifying MessagePersistence (DeliveryModes)

  • 8/8/2019 J2EE JMS

    100/120

    Two Delivery Modes

    PERSISTENT delivery mode Default

    Instructs the JMS provider to take extra careto ensure that a message is not lost in transitin case of a JMS provider failure

    NON_PERSISTENT delivery model

    Does not require the JMS provider to storethe message

    Better performance

  • 8/8/2019 J2EE JMS

    101/120

    How to Specify Delivery Mode

    SetDeliveryMode method of theMessageProducer interface producer.setDeliveryMode(DeliveryMode.NON

    _PERSISTENT);

    Use the long form of the send or thepublish method

    producer.send(message,DeliveryMode.NON_PERSISTENT, 3,10000);

  • 8/8/2019 J2EE JMS

    102/120

    Setting MessagePriority Levels

  • 8/8/2019 J2EE JMS

    103/120

  • 8/8/2019 J2EE JMS

    104/120

    Allowing Messages toExpire

  • 8/8/2019 J2EE JMS

    105/120

    How to set Message Expiration

    Use the setTimeToLive method of theMessageProducer interface producer.setTimeToLive(60000);

    Use the long form of the send or thepublish method producer.send(message,

    DeliveryMode.NON_PERSISTENT, 3,60000);

  • 8/8/2019 J2EE JMS

    106/120

    Creating DurableSubscriptions

  • 8/8/2019 J2EE JMS

    107/120

    Maximum Reliability

    To ensure that a pub/sub applicationreceives all published messages Use PERSISTENT delivery mode for the

    publishers In addition, use durable subscriptions for the

    subscribers

    Use the

    Session.createDurableSubscribermethod to create a durable subscriber

    How Durable Subscription

  • 8/8/2019 J2EE JMS

    108/120

    How Durable SubscriptionWorks A durable subscription can have only one active

    subscriber at a time

    A durable subscriber registers a durablesubscription by specifying a unique identity that is

    retained by the JMS provider Subsequent subscriber objects that have the same

    identity resume the subscription in the state inwhich it was left by the preceding subscriber

    If a durable subscription has no active subscriber,the JMS provider retains the subscription'smessages until they are received by thesubscription or until they expire

  • 8/8/2019 J2EE JMS

    109/120

    Transactions in JMS

    T i i JMS

  • 8/8/2019 J2EE JMS

    110/120

    Transactions in JMS

    Transaction scope is only betweenclient and Messaging system notbetween clients a group of messages are dispatched as a

    unit (on the sender side)

    a group of messages are retrieved as a unit(on the receiver side)

    Local and Distributed transactions

    L l T i i JMS

  • 8/8/2019 J2EE JMS

    111/120

    Local Transactions in JMS

    Local transactions are controlled by Sessionobject

    Transaction begins when a session is created

    There is no explicit begin transaction method Transaction ends when Session.commit() or

    Session.abort() is called

    Transactional session is created by specifyingappropriate flag when a session is created QueueConnection.createQueueSession(true, ..)

    TopicConnection.createTopicSession(true, ..)

    Di ib d T i i JMS

  • 8/8/2019 J2EE JMS

    112/120

    Distributed Transactions in JMS

    Coordinated by a transactional manager

    Applications will control the transaction

    via JTA methods Use of Session.commit() and Session.rollback()

    is forbidden

    Messaging operations can be combined

    with database transactions in a singletransaction

  • 8/8/2019 J2EE JMS

    113/120

    MessageSelector

    JMS M S l t

  • 8/8/2019 J2EE JMS

    114/120

    JMS Message Selector

    (Receiver) JMS application uses aselector to select only the messagesthat are of interest

    A selector is essentially a SQL92string that specifies selection (orfiltering) rule A Teller object listening for Account objects

    as messages may be required to dosomething only when the account balancedrops below a $1000

    Example: JMS Message

  • 8/8/2019 J2EE JMS

    115/120

    Example: JMS MessageSelectors The selector cannot reference the

    contents of a message

    It can access the properties and header

    Examples JMSType==wasp

    phone LIKE 223

    price BETWEEN 100 AND 200 name IN(sameer,tyagi)

    JMSType IS NOT NULL

  • 8/8/2019 J2EE JMS

    116/120

    Messaging Featuresnot Defined in JMS

    Messaging Features Not

  • 8/8/2019 J2EE JMS

    117/120

    Messaging Features Not

    Defined in JMS (No APIs) Encryption

    JMS spec assumes messaging system

    handles it Access control

    JMS spec assumes messaging systemhandles it

    Load balancing

    Administration of queues and topics

  • 8/8/2019 J2EE JMS

    118/120

    JMS and Message-Driven Bean (MDB)

    JMS d MDB

  • 8/8/2019 J2EE JMS

    119/120

    JMS and MDB

    JMS ProviderEJB Container

    Destin-ation

    Consumer

    Instances

    Msg-drivenBean Class

  • 8/8/2019 J2EE JMS

    120/120