Bài giảng Lập trình mạng 2 - Java message service - Nguyễn Xuân Vinh

Tóm tắt Bài giảng Lập trình mạng 2 - Java message service - Nguyễn Xuân Vinh: ...or two types of messaging models, publish-and-subscribe and point-to-point queuing JMS Messaging Models25Messaging clients in JMS are called JMS clients The messaging system - the MOM - is called the JMS provider A JMS application is a business system composed of many JMS clients and, generally, one...AULT_PRIORITY, 1800000);39Publish-and-SubscribePublish-and-Subscribe Example: WholeSalerpublic void onMessage(Message message) {try {TextMessage textMessage = (TextMessage) message;String text = textMessage.getText();.} catch (java.lang.Exception rte) { rte.printStackTrace();}}40Publish-and-Subscrib...eveloper with more information about the message There are three basic categories of message properties Application-specific propertiesJMS-defined propertiesProvider-specific properties 58Message TypesMessage typeMessage bodyMessageNo body TextMessageA standard Java stringObjectMessageA serializable...

ppt85 trang | Chia sẻ: havih72 | Lượt xem: 203 | Lượt tải: 0download
Nội dung tài liệu Bài giảng Lập trình mạng 2 - Java message service - Nguyễn Xuân Vinh, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
Java Message ServicePresenter: Nguyễn Xuân VinhInformation Technology FacultyNong Lam University2Content Understanding The Messaging Paradigm1Concepts and Architecture of JMS2JMS Messaging Models3Anatomy of a JMS Message4JMS Features5JMS Providers63Understanding The Messaging ParadigmSome concepts of messaging systemCentralized ArchitectureDecentralized Architecture4Some concepts of messaging systemMessaging systems allow different software applications to communicate with each other, generically referred to enterprise messaging systems, or Message-Oriented Middleware A key concept of enterprise messaging is messages are delivered asynchronously from one system to others over a network5Enterprise messaging systems allow two or more applications to exchange information in the form of messages A message is a self-contained package of business data and network routing headers In all modern enterprise messaging systems, applications exchange messages through virtual channels called destinations. Some concept of messaging system6In asynchronous messaging, applications use a simple API to construct a message, then hand it off to the Message-Oriented Middleware for delivery to one or more intended recipients. Some concept of messaging systemFigure 1.1. Message-Oriented Middleware 7Some concept of messaging systemRPC vs Asynchronous MessagingRPC attempts to mimic the behavior of a system that runs in one process A failure on one system has an immediate and debilitating impact on other systems8RPC vs Asynchronous MessagingBusinessApplication ARPCClient/ServerBusinessApplication DRPCClient/ServerBusinessApplication BRPCClient/ServerBusinessApplication CRPCClient/ServerRequires n * (n-1) / 2 connectionsSome concept of messaging system9Some concept of messaging systemRPC vs Asynchronous MessagingA fundamental concept of MOM is that communication between applications is intended to be asynchronous In MOM, each subsystem is decoupled from the other systems 10Some concept of messaging systemRPC vs Asynchronous MessagingCentralized message server (hub and spoke)JMS ClientMessage ServerJMS ClientJMS ClientJMS ClientJMS ClientJMS ClientJMS ClientLocal "server"JMS ClientLocal "server"JMS ClientLocal "server"JMS ClientApplication ALocal "server"Application BApplication CApplication DRouterDecentralized message server (IP multicast)11Centralized ArchitectureA message server is responsible for delivering messages from one messaging client to other messaging clientsThe message server decouples a sending client from other receiving clients 12A centralized architecture uses a hub-and-spoke topology The hub-and-spoke architecture lends itself to a minimal amount of network connections while still allowing any part of the system to communicate with any other part of the system Centralized Architecture13Decentralized ArchitectureAll decentralized architectures currently use IP multicast at the network level Some of the server functionality (persistence, transactions, security) is embedded as a local part of the client, while message routing is delegated to the network layer by using the IP multicast protocol 14IP multicast allows applications to join one or more IP multicast groups; each group uses an IP network address that will redistribute any messages it receives to all members in its group The network handles routing automatically Decentralized Architecture15ContentUnderstanding the Messaging Paradigm1Concepts and Architecture of JMS2JMS Messaging Models3Anatomy of a JMS Message4JMS Features5JMS Providers616Concepts and Architecture of JMSWhat is JMS? Architecture of JMS17What is JMS?The JMS (Java Message Service) is an API for enterprise messaging created by Sun Microsystems JMS is not a messaging system itself JMS abstracts access to MOMs 18Supports message production, distribution, deliverySupported message delivery semanticsSynchronous or AsynchronousTransactedGuaranteedDurableWhat is JMS?19Architecture of JMSJMS architectural componentsJMS clientsNon-JMS clientsMessagesJMS provider (Messaging systems)JNDI administered objectsDestinationConnectionFactory20Architecture of JMS applicationArchitecture of JMS21A JMS ApplicationJMS ClientsJava programs that send/receive messagesMessages Administered ObjectsPreconfigured JMS objects created by an admin for the use of clientsConnectionFactory, Destination (queue or topic)JMS ProviderMessaging system that implements JMS and administrative functionalityArchitecture of JMS22JMS AdministrationArchitecture of JMSAdministrativeToolJNDI NamespaceJMS ClientBindLookupLogicalConnectionJMS Provider23ContentUnderstanding the Messaging Paradigm1Concepts and Architecture of JMS2JMS Messaging Models3Anatomy of a JMS Message4JMS Features5JMS Providers624JMS provides for two types of messaging models, publish-and-subscribe and point-to-point queuing JMS Messaging Models25Messaging clients in JMS are called JMS clients The messaging system - the MOM - is called the JMS provider A JMS application is a business system composed of many JMS clients and, generally, one JMS provider A JMS client that produces a message is called a producerA JMS client that receives a message is called a consumer JMS Messaging Models26JMS componentsJMS Messaging ModelsMessage ServerMessageMessageDestinationJMS ClientConnectionSessionProducerJMS ClientConnectionSessionConsumer27Connections and sessionsA connection connects to a message serverCan create one or more sessions within a connectionJMS ClientConnectionSessionSessionSessionJMS Messaging Models28Creating connections and sessionsMessage ServerJNDI StoreJMS ClientConnectionSessionSessionSessionConnectionFactorycreateConnectionFactoriesDestinationsJMS Messaging Models29JMS Messaging ModelsPublish-and-SubscribePoint-to-Point30Publish-and-SubscribeOne producer can send a message to many consumers through a virtual channel called a topic Consumers, which receive messages, can choose to subscribe to a topic Any messages addressed to a topic are delivered to all the topic's consumers Every consumer receives a copy of each message 31Messages are automatically broadcast to consumers without them having to request or poll the topic for new messages Durable subscriptions allow consumers to disconnect, and later reconnect and collect messages that were published while they were disconnected Publish-and-Subscribe32Publish-and-SubscribePublisherTopicSubscriberSubscriberMSGMSGMSGSubscribe to a Topic33Publish-and-SubscribeJMS Pub-Sub Classes34Publish/Subscribe Applicationsubscribe (“AAPL”);subscribe (“SUN”);subscribe (“AAPL”);subscribe (“SUN”);publish (“AAPL”, 29.2);publish(“AAPL”, 29.3);publish (“SUN”, 43.0);publish(“SUN”, 42.7);Publish-and-Subscribe35Publish-and-SubscribePublish-and-Subscribe ExampleMessage ServerWholesalerRetailer 1Retailer 2Update price(publish)Order product(send)36Publish-and-SubscribePublish-and-Subscribe Example: WholesalerProperties env = new Properties();env.put("BROKER", broker);InitialContext jndi = new InitialContext(env);TopicConnectionFactory factory = (TopicConnectionFactory) jndi.lookup("TopicConnectionFactory");TopicConnection connect = 	factory.createTopicConnection(username, password);Topic hotDealsTopic = (Topic) jndi.lookup("Hot Deals");TopicPublisher publisher = pubSession.createPublisher(hotDealsTopic);37Publish-and-SubscribePublish-and-Subscribe Example: WholeSalerTopicSession pubSession = connect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);TopicSession subSession = connect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);TemporaryTopic buyOrdersTopic =	subSession.createTemporaryTopic();TopicSubscriber subscriber = 	subSession.createSubscriber(buyOrdersTopic);38Publish-and-SubscribePublish-and-Subscribe Example: WholeSaler//Update price StreamMessage message = pubSession.createStreamMessage();message.writeString(dealDesc);message.setJMSReplyTo(buyOrdersTopic);publisher.publish(message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, 1800000);39Publish-and-SubscribePublish-and-Subscribe Example: WholeSalerpublic void onMessage(Message message) {try {TextMessage textMessage = (TextMessage) message;String text = textMessage.getText();.} catch (java.lang.Exception rte) {	rte.printStackTrace();}}40Publish-and-SubscribePublish-and-Subscribe Example: RetailerTextMessage textMsg = session.createTextMessage();textMsg.setJMSCorrelationID("DurableRetailer");Topic buytopic = (Topic) message.getJMSReplyTo();publisher = session.createPublisher(buytopic);publisher.publish(textMsg, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, 1800000);41Publish-and-SubscribePublish-and-Subscribe Example	Demo42Publish-and-SubscribePublish-and-Subscribe Example: ChatTopicMSGMSGMSGMSG43Point-to-PointIn the p2p model, the producer is called a sender and the consumer is called a receiver Messages are exchanged through a virtual channel called a queue Each message is delivered only to one receiver 44Messages are orderedQueue can have multiple consumers but each message is consumed only onceThere is no coupling of the producers to the consumersPoint-to-Point45P2P messages are always delivered, regardless of receiver connection stateP2P Queue can push or pull messages with regard to the receiveronMessage() – callback, asyncreceive() – method, syncPoint-to-Point46Point-to-PointSenderQueuePotentialReceiverPotentialReceiverMSGMSGConsumes messageQueuePotentialReceiverPotentialReceiverQueuePotentialReceiver47Browsing a queuenextElement();QueueBrowsergetEnumeration();Message1Message2Message3Message4EnumerationPoint-to-Point48Message Queuing ApplicationPoint-to-Point49P2P and Pub/SubBased on the concept of sending a message to a named destination There is no direct coupling of the producers to the consumers The pub/sub model is based on a push model. While a p2p queue can either push or pull messages50In the pub/sub model, multiple consumers that subscribe to the same topic each receive their own copy of every message addressed to that topicIn the p2p model, multiple consumers can use the same queue, but each message delivered to the queue can only be received by one of the queue's consumers P2P and Pub/Sub51JMS API Programming ModelConnectioncreatescreatescreatesMsgDestinationreceives fromsends toConnectionFactoryDestinationMessageConsumerSessionMessageProducercreates52ContentUnderstanding the Messaging Paradigm1Concepts and Architecture of JMS2JMS Messaging Models3Anatomy of a JMS Message4JMS Features5JMS Providers653The Message is the most important part of the entire JMS specification A JMS message both carries application data and provides event notification Anatomy of a JMS Message54PayloadHeaderPropertiesAnatomy of a JMS Message55Used for identifying and routing messagesTypically name/value pairsJMS headers are divided into two large groupsAutomatically assigned headersDeveloper assigned headersHeaders56HeadersAutomatically assigned headersJMSDestinationJMSDeliveryModeJMSMessageIDJMSTimestampJMSExpirationJMSRedeliveredJMSPriorityDeveloper-assigned headersJMSReplyToJMSCorrelationIDJMSType57PropertiesAct like additional headers that can be assigned to a message Provide the developer with more information about the message There are three basic categories of message properties Application-specific propertiesJMS-defined propertiesProvider-specific properties 58Message TypesMessage typeMessage bodyMessageNo body TextMessageA standard Java stringObjectMessageA serializable Java objectMapMessageA set of name/value pairs where values are Java primitivesStreamMessageA stream of Java primitivesBytesMessageA stream of uninterpreted bytes59When messages are delivered, the body and properties of the message is made read-only Message Types60Message SelectorsAllows a JMS consumer to be more selective about the messages it receives from a particular destination Use message properties and headers as criteria in conditional expressions Based on a subset of the SQL-92 conditional expression syntax 61Example of Message SelectorAge = 100.00 AND LName = 'Smith' Identifiers Literals Comparison OperatorsMessage Selectors62ContentUnderstanding the Messaging Paradigm1Concepts and Architecture of JMS2JMS Messaging Models3Anatomy of a JMS Message4JMS Features5JMS Providers663JMS FeaturesGuaranteed MessagingTransactionsAcknowledgments and Failures64There are three main parts to guaranteed messaging Message autonomyStore-and-forwardMessage acknowledgmentGuaranteed Messaging65Message autonomyMessages are self-contained autonomous entities Guaranteed Messaging66Store-and-forwardWhen messages are marked persistent, it is the responsibility of the JMS provider to utilize a store-and-forward mechanism to fulfill its contract with the sender Guaranteed Messaging67Message acknowledgmentA key part of guaranteed messaging Servers acknowledge the receipt of messages from JMS producers JMS consumers acknowledge the receipt of messages from servers Guaranteed Messaging68Acknowledgment ModesAUTO ACKNOWLEDGECLIENT ACKNOWLEDGEDUPS OK ACKNOWLEDGEGuaranteed Messaging69Acknowledge ModesAUTO ACKNOWLEDGESession automatically acknowledges a client’s receipt of a messageReturns from a call to receive or the MessageListener it has called to process the message successfullyGuaranteed Messaging70Acknowledge ModesAUTO ACKNOWLEDGECLIENT ACKNOWLEDGEClient acknowledges a message by calling the message’s acknowledge methodAcknowledging a consumed message automatically acknowledges the receipt of all messages that have been delivered by the sessionGuaranteed Messaging71Acknowledge ModesAUTO ACKNOWLEDGECLIENT ACKNOWLEDGEDUPS OK ACKNOWLEDGELazily acknowledge the delivery of messagesCan cause duplicated messagesWe handle the same way as AUTO ACKNOWLEDGEGuaranteed Messaging72TransactionsTransacted Session: ProducerJMS provider will not start delivery of the messages to its consumers until the producer has issued a commit( ) on the session73Transacted Session: ProducerProducerMessage ServerConsumerBefore commit( )Upon commit( )Message ServerTransacted sessionTransactions74Transacted Session: ConsumerJMS provider hold messages delivered until the receiver issues a commit( ) on the session object Transactions75Transacted Session: ConsumerTransactionsMessage ServerConsumerBefore commit( )Upon commit( )Message ServerConsumer12Deliver messagesConsume messages12Acknowledge messagesDelete messages if all recipients have acknowledged76Distributed TransactionsMessage ServerJNDI StoreJMS ClientXAConnectionXASessionXASessionXASessionXAConnectionFactorycreateConnectionFactoriesDestinationsTransactions77Lost connectionWhen a network connection between the client and server is lost, a JMS provider must make every reasonable attempt to re-establish the connection Acknowledgments and Failures78Recovering from a lost connectionClient runtimeMessage ServerExceptionListeneronException()ReconnectAcknowledgments and Failures79JMS with EJBMessage–Driven BeanActs as a listener for the JMS, processing messages asynchronouslySpecialized adaptation of the JMS API used in the context of J2EE applications80JMS with EJBMessage-driven bean Life Cycledoes not existpooled1: newInstance()2: setMessageDrivenContextContext()3: ejbCreate()ejbRemove()onMessage()81JMS with EJBJMS with EJB Example82JMS with EJBEJB is a server-side component that encapsulates the business logic of an applicationEJB simplifies the development of large, distributed applicationsEJB Container provides system-level servicese.g. transaction management, authorizationBeans have the control logicthin client applicationsPortable componentscan run on any compliant J2EE server83ContentUnderstanding the Messaging Paradigm1Concepts and Architecture of JMS2JMS Messaging Models3Anatomy of a JMS Message4JMS Features5JMS Providers684JMS ProvidersIBM: MQSeriesProgress: SonicMQ Fiorano: FioranoMQ Softwired: iBus Sun Microsystems: Java Message Queue BEA: WebLogic Server ExoLab: OpenJMS HỎI ĐÁP

File đính kèm:

  • pptbai_giang_lap_trinh_mang_2_java_message_service_nguyen_xuan.ppt