Download presentation
Presentation is loading. Please wait.
Published byAlicia Carroll Modified over 9 years ago
1
Communication in Distributed Systems Cheng-Zhong Xu
2
© C. Xu, 1998-2011 Taxonomy Communication Point-to-pointMulticast group comm Two-way comm One-way comm Socket prog RPC/RMI Message-oriented
3
© C. Xu, 1998-2011 Outline u TCP/UDP socket programming u RPC/RMI programming –RPC: Remote Procedure Call –RMI: Remote Method Invocation u Distribute Objects –Local object vs remote object u Message-oriented comm
4
© C. Xu, 1998-2011 Limitations of Socket Programming u Limited support for data structure in comm –In Java TCP/UDP programming, data in transmission is defined as a stream of bytes –client and server are coupled in development: they need to know how the data are interpreted at other side u Limited support for heterogeneity –Network protocols: Internet protocol masks the differences between networks, but –computer hardware: e.g. data types such as integers can be represented differently –operating systems, e.g. the API to IP differs from one OS to another –programming languages, data structures (arrays, records) can be represented differently –implementations by different developers, »they need agreed standards so as to be able to inter-work
5
© C. Xu, 1998-2011 Architectural heterogeneity: an example Representations of integer 5 and String “JILL” on different machines: Original message on the Pentium (little endian) The message after receipt on the SPARC (big endian) The message after being inverted. The little numbers in boxes indicate the address of each byte Integers are reversed by byte ordering, but strings are not!!
6
© C. Xu, 1998-2011 Remote Procedure Call (RPC) Remote Method Invocation (RMI) u Middleware provides a simple programming abstraction and masks heterogeneity of client and server systems u Similar interface as in procedure call or method invocation between client and service –client sends command and arguments –server computes –Server sends back reply data u Implementation of the procedures or methods are on remote servers
7
© C. Xu, 1998-2011 Conventional Procedure Call a)Parameter passing in a local procedure call: the stack before the call to read b)The stack while the called procedure is active For example, count = read(fd, buf, nbytes);
8
© C. Xu, 1998-2011 Remote Procedure Call (RPC) u Build a mechanism, which allows clients –call procedures over a network as if the code was stored and executed locally u The mechanism automates the writing of data-handling and formatting code u Advantages: fewer errors, faster to code and evolve interfaces
9
© C. Xu, 1998-2011 RPC Structure: Client/Server Proxies (stub, skeleton) client program server program client stub server skeleton network call return 1. Client procedure calls client stub in normal way 2. Client stub builds message, calls local OS 3. Client's OS sends message to remote OS 4. Remote OS gives message to server stub/skel 5. Server stub unpacks parameters, calls server 6. Server does work, returns result to the stub 7. Server stub packs it in message, calls local OS 8. Server's OS sends message to client's OS 9. Client's OS gives message to client stub 10. Stub unpacks result, returns to client
10
© C. Xu, 1998-2011 Passing Parameters u Steps involved in doing remote computation through RPC 2-8
11
© C. Xu, 1998-2011 Outline u TCP/UDP socket programming u RPC/RMI programming –RPC: Remote Procedure Call –RMI: Remote Method Invocation u Distribute Objects –Local object vs remote object u Message-oriented comm
12
© C. Xu, 1998-2011 Distributed Objects u An object is an individual unit of run-time data storage used as the basic building block of programs. –Each object is capable of receiving msgs, processing data, and sending msgs to other objects; methods together form the object’s interface with the outside world or other objects. –A class is the blueprint from which individual objects are created. u Distributed objects have a separation between interfaces and objects that implement the interfaces; interfaces and the objects are in different machines. u Allow programs to treat remote objects just like local objects –remote references –remote invocation u First good impl: DEC SRC network objects for Modula-3 u Recent implementation: Java Remote Method Invocation
13
© C. Xu, 1998-2011 Organization of Distributed Objects u Separate proxy for each remote object that is referenced u proxy looks just like real object. but loaded at run-time when remote object is to be bound. –implements the same interface u proxy’s methods do RPC to real object –handle arguments, return values, exceptions correctly u proxy code generated by RMI compiler
14
© C. Xu, 1998-2011 Remote Object References u Naming a remote object (“global address”) –machine (IP address) where actual object resides –port number, identifying the server that manages the object –(boot time) –unique object ID number (generated by server) –Object references can be passed between processes, as parameters to method invocations u Before invocation, object ref. must first bind to its object. Binding leads to a placement of corresponding proxy u Programs referenced a remote object by using stand-in proxy object
15
© C. Xu, 1998-2011 Remote Invocation u when a proxy method is invoked: –invocation message sent to remote process »contains global address of object, method ID, arguments –remote process invokes real object –return message sent back to proxy object »contains return value or exception –proxy method call returns correct value, or throws correct exception u Under the Hood u each process keeps a table of all proxy objects –maps global address to proxy object u use table to maintain one-to-one mapping from proxy object to remote object u interactions with garbage collection
16
© C. Xu, 1998-2011 compiler/ linker compiler/ linker Building an RMI App client code server interface stub generator server skeleton client stub client app server app Server code server impl
17
© C. Xu, 1998-2011 RMI Binding (rmi registry) u How does a client find the service code u Registry to keep track of distributed objects –simply a name repository –provides a limited central management point for RMI u Server binds methods to names in the reg u Client looks up names in the reg for availability of an object
18
© C. Xu, 1998-2011 Interface Definition import java.rmi.*; public interface myServer extends Remote { public void doSomething( … ) throws RemoteException; } u All remote objects are referenced through interfaces –It extends the Remote interface as all RMI interfaces must –Methods must throw RemoteException
19
© C. Xu, 1998-2011 // myClient // myServer object has registered itself as “xuObject” import java.rmi.*; import java.rmi.server.*; public class myClient { public static void main( String[] args ) { System.setSecurityManager( new RMISecurityManager() ); try { myServer ro= (myServer)Naming.lookup(“xuObject”); ro.doSomething(); } catch (Exception e) {} }
20
© C. Xu, 1998-2011 Notes u All RMI-based app need to import –java.rmi and java.rmi.server packages u Inside the main method, the first thing is set the Java security manager, which grant or deny permissions on the operations u create a try/catch block that performs the remote method invocation
21
© C. Xu, 1998-2011 // myServer implementation import java.rmi.*; import java.rmi.server.*; import java.rmi.registry.*; public class myServerImpl extends UnicastRemoteObject implements myServer { public myServerImpl() throws RemoteException{ } public void doSomething(… ) throws RemoteException{… …} public static void main( String[] args) { System.setSecurityManager( new RMISecurityManager()); try { myServerImpl obj = new myServerImpl(); Naming.rebind(“xuObject”, obj); System.out.println(“doSomething bound in registry”); }catch (Exception e) {} }
22
© C. Xu, 1998-2011 Notes u myServerImpl extends –java.rmi.server.UnicastRemoteObject class, which defines a non-replicated remote object whose references are valid only while the myServer process is alive (Transient Objects). –It supports point-to-point active object reference via TCP streams. u Bind vs rebind u A remote implementation must have a zero- argument constructor
23
© C. Xu, 1998-2011 Deployment u Generate stub and skeleton –rmic myServerImpl, which generates »myServerImpl_Stub.class, myServerImpl_Skel.class –Since JDK 5.0, stub classes can be generated on- demand at runtime u rmiregistry –starts the registry service in the background u java ServerImpl –starts the server, which registers the remote object with the registry u java Client
24
© C. Xu, 1998-2011 Passing Arguments u Passing primitive types (int, boolean, etc.) u Remote object vs. non-remote objects –remote object is an instance of RemoteObject –remote object refers to an object whose method can be invoked from another JVM. –Remote objects passed by reference, while non- remote objects passed by copy u A difference between RPC and RMI –passing objects, –passed object may interact with receipt itself
25
© C. Xu, 1998-2011 Parameter Passing u Remote object vs Local Object –Pass-by-value is ok for all distributed object references, but not efficient u The situation when passing an object by reference or by value –E.g. Client on machine A calls a method of remote object in machine C, which contains two parameters: O1 in machine A and O2 in machine B
26
© C. Xu, 1998-2011 Passing objects u Object Serialization –To be passed between client/server, objects have to be serialized u For example, –CloudServer, which do jobs for clients in clouds –Different clients may ask CloudServer do different jobs –Each job is specified in arguments passed from a client to the server
27
© C. Xu, 1998-2011 //Task.java import java.io.*; public class Task implements Serializable{ public Object execute() { return null; } } //foo.java public class foo extends Task{ int n; public foo (int m) {n=m;} public Object execute() { return new Integer( n*n ); }
28
© C. Xu, 1998-2011 // CloudServer.java import java.rmi.*; import java.util.*; public interface CloudServer extends Remote { Object execute( Task o) throws RemoteException }
29
© C. Xu, 1998-2011 // CloudServerImpl.java import java.rmi.*; import java.io.*; import java.rmi.server.*; public class CloudServerImpl implements CloudServer { public CloudServerImpl() throws RemoteException{} public Object execute( Task t) throws RemoteException { return t.execute(); } public static void main (String args[]) { System.setSecurityManager( new RMISecurityManager()); try { CloudServer csr = new CloudServerImpl(); Naming.rebind(“CloudServer”, csr); } catch (IOException ioe) {} }
30
© C. Xu, 1998-2011 // example.java // java example registry-host import java.rmi.*; import java.io.*; public class example{ public static void main( String[] args ) throws RemoteException { System.setSecurityManager( … ); new example(args[0]); } public example( String host ) { try { CloudServer csr = (CloudServer) Naming.lookup(“rmi://”+host+“/CloudServer”); System.out.println( csr.execute( new foo(10) ); catch (IOException ioe) {} … … }
31
© C. Xu, 1998-2011 Running on different machines u Server site –CloudServer.class –CloudServerImpl.class –CloudServerImpl_Stub.class –CloudServerImpl_Skel.class –Task.class u java CloudServerImpl u Client site –CloudServer.class –example.class –CloudServerImpl_Stub.class –Task.class –foo.class At client site java -Djava.rmi.server.codebase=‘…’ example server
32
© C. Xu, 1998-2011 Remote Object References u Asynchronous Client/Server Comm –Client calls CloudServer’s asynExecute(…) –On the completion of the work, the CloudServer notifies the client of the result u Client itself is declared as a Remote Object, which reference is passed to CloudServer u CloudServer calls workCompleted(…) of the remote object.
33
© C. Xu, 1998-2011 // CloudServer.java import java.rmi.*; import java.util.*; public interface CloudServer extends Remote { Object execute( Task work ) throws RemoteException void asynExecute( Task work, WorkListener listener) throws RemoteException }
34
© C. Xu, 1998-2011 Public class CloudServerImpl extends UnicastRemoteObject implements CloudServer { … public void asynExecute(Task work, WorkListener listener) throws RemoteException { Object result = work.execute(); listener.workCompleted( work, result ); }
35
© C. Xu, 1998-2011 // WorkListener.java public interface WorkListener extends Remote { public void workCompleted( Task request, Object result ) throws RemoteException; } WorkListener Remote Interface Example.java will be modified to implement the remote interface. This turns example into a remote object
36
© C. Xu, 1998-2011 import java.rmi.*; import java.io.*; public class example extends UnicastRemoteObject implements WorkListener{ public static void main( ) throws RemoteException {…} public void workCompleted( Task t, Object result) throws RemoteException { System.out.println(“Async work result = “ + result); } public example ( String host ) throws RemoteException { try { CloudServer csr = (CloudServer) Naming.lookup(“rmi://”+host+“/CloudServer”); csr.asynExecute( new foo(10), this ); catch (IOException ioe) {} }
37
© C. Xu, 1998-2011 Remarks u Asynchronous RPC: A client and server interacting through two asynchronous RPCs Asynchronous RMI ??
38
© C. Xu, 1998-2011 RPC vs RMI u RMI supports system-wide object references u RMI can have object-specific stubs, not necessarily have general-purpose client-side and server-side stubs u Pass objects as arguments (object migration) u Migrated objects can interact with both original and new hosts
39
© C. Xu, 1998-2011 Mobile Objects u Objects be passed as arguments –Single-hop vs multi-hop migration –Dispatched by its host, or migrated according to its own itinerary u Mobile objects can be performed on hosts (cloud servers) according to their own agenda, under a security sandbox –access to local computing and data resources u Mobile objects can communicate back to their home hosts. Weak mobility Stop before migration, and restart on arrival at a new server; running status not transferred Strong mobility Suspend before migration, and resume on arrival at a new server; running status carried over
40
© C. Xu, 1998-2011 Naplet: A mobile object middleware system Naplet 0.2 source code available http://www.ece.eng.wayne.edu/~czxu/ software/naplet.html u Structured Itinerary Mechanism –Sequential/parallel/alternative visit of a group of servers u Naplet directory based location + Forward Pointer u Message-oriented communication u Persistent comm between mobile objects u Un/secure execution –Multithreaded objects –Secure access to local resource u Java based
41
© C. Xu, 1998-2011 Local Object vs Remote Object u Cloning: remote object can be cloned only by the server. Proxies of the object are not cloned. u Synchronization: –synchronizing block in the client-side requires support for distributed synchronization –synchronizing block in the server-side causes problems when a client crashes when its invocation is being handled –Java RMI restricts blocking on remote objects to the proxies only. No protection against simultaneous access via different proxies u During an RMI, local objects are passed by value, whereas remote objects are passed by reference.
42
© C. Xu, 1998-2011 Static and Dynamic Invocation u Static invocation uses pre-defined interface definitions –It requires that the interfaces of an object are known when the client application is being developed –If interfaces change, the client application must be recompiled u Dynamic invocation: method invocation is composed at run-time in the form like invoke(object, method, in_param, out_param) –Often used to implement a generic distributed services: call different services based on different input. –E.g. Generic computational server.
43
© C. Xu, 1998-2011 Taxonomy Communication Point-to-pointMulticast group comm Two-way comm One-way comm Socket prog RPC/RMI Message-oriented
44
© C. Xu, 1998-2011 Message-Oriented Persistent Communication
45
© C. Xu, 1998-2011 Organization of Comm System Examples: Email --- Client/Outbound Mail Server/Inbound Server MPI --- Message Passing Layer Difference??
46
© C. Xu, 1998-2011 Another Example of Persistent Comm u Persistent communication of letters back in the days of the Pony Express. Although the means of transportation and the means by which letters are sorted have changed, the mail principle remains the same
47
© C. Xu, 1998-2011 Persistence and Synchronicity u Persistent vs Transient Communication –Persistent: submitted messages are stored by the comm. system as long as it takes to deliver it the receiver –Transient: messages are stored by the comm system as long as the sending and receiving app. are executing. u Asynchronous vs synchronous –Sync: a client is blocked until its message is stored in a local buffer at the receiving host, or actually delivered to the receiver –Async: A sender continues immediately after it has submitted its message for transmission. (The message is stored in a local buffer at the sending host, or otherwise at the first communication server.
48
© C. Xu, 1998-2011 a) Persistent asynchronous communication E.g. Email b) Persistent synchronous communication (??) ( a weaker form: when the sender is blocked until its message is stored at receiver-side comm server )
49
© C. Xu, 1998-2011 c) Transient asynchronous communication (e.g. UDP, asynchronous RPC). Transmission fails if the receiver is not executing at the time the msg arrives. d) Receipt-based transient synchronous communication. Sender is blocked until the msg is stored in a local buffer at the receiving host. (Example?) 2-22.2
50
© C. Xu, 1998-2011 e) Delivery-based transient synchronous communication at message delivery. (Sender is blocked until the msg is delivered to the receiver) f) Response-based transient synchronous communication (e.g. RPC and RMI) (Sender is blocked until it receives a reply msg from the receiver)
51
© C. Xu, 1998-2011 Different Forms of Communication u Persistent Asynchronous u Persistent Synchronous u Transient Asynchronous u Transient Synchronous –Receipt-based (weakest, e.g. async. RPC) –Delivery-based –Response-based (strongest, e.g. RPC) u Need for persistent comm. in middleware, large- scale system –Components of a large scale distributed system may not always be immediately accessible –Failure should be masked with a recovery procedure –But, persistent comm. incurs long delays
52
© C. Xu, 1998-2011 Message-Oriented Transient Comm. u Socket is a communication endpoint to which an appl can write data to and from which incoming data can be read u Socket primitives for TCP/IP. PrimitiveMeaning SocketCreate a new communication endpoint BindAttach a local address to a socket ListenAnnounce willingness to accept connections AcceptBlock caller until a connection request arrives ConnectActively attempt to establish a connection SendSend some data over the connection ReceiveReceive some data over the connection CloseRelease the connection
53
© C. Xu, 1998-2011 Berkeley Sockets u Connection-oriented communication pattern using sockets.
54
© C. Xu, 1998-2011 MPI: Another Transient Comm u Basic message-passing primitives of MPI. PrimitiveMeaning MPI_bsendAppend outgoing message to a local send buffer of MPI runtime MPI_sendSend a message and wait until copied to local or remote buffer MPI_ssendSend a message and wait until receipt starts MPI_sendrecvSend a message and wait for reply MPI_isendPass reference to outgoing message, and continue MPI_issendPass reference to outgoing message, and wait until receipt starts MPI_recvReceive a message; block if there are none MPI_irecvCheck if there is an incoming message, but do not block
55
© C. Xu, 1998-2011 Synchrony in MPI u MPI_bsend Transient synchronous u MPI_send (blocking send) –Block the caller until the msg be copied to MPI runtime system at the receiver’s side; Receipt-based transient comm –or until the receiver has initiated a receive operation delivery-based transient comm u MPI_ssend delivery-based u MPI_sendrecv response-based
56
© C. Xu, 1998-2011 Message Queuing Model u MQ: a software-engineering component used for interprocess comm. It utilizes a queue for messaging—the passing of control or of content. [Wikipedia] u MQ provides a Persistent Asynchronous comm protocol –Sender and receiver do not need to connect to the msg queue at the same time; msgs placed on the queue are stored until the recipient retrieves them. –Most msg queues have set limits on the size of data that can be transmitted in a single msg. Those with no such limits are often referred to as mailboxes.
57
© C. Xu, 1998-2011 u Four combinations for loosely-coupled comm. using queues (sender and receiver can execute completely independently of each other) 2-26 MQ Model
58
© C. Xu, 1998-2011 MQ: Interface to a Queue PrimitiveMeaning PutAppend a message to a specified queue (non-blocking) GetBlock until the specified queue is nonempty, and remove the first message PollCheck a specified queue for messages, and remove the first. Never block. Notify Install a handler to be called when a message is put into the specified queue. One-way Communication Primitives: Addressing: System wide unique destination queue Active message: The handler to be executed on arrival at the dest. Mobile object: messages in principle contains any data. How about objects?
59
© C. Xu, 1998-2011 Msg Oriented Middleware (MOM) u Many impl function internally in OS or appl –In UNIX: msgctrl(), msgget(), msgsnd() u Distributed impl across different systems for msg passing –Enhanced fault resilient: msgs don’t get lost even in the event of a system failure. u Examples: –IBM’s WebSphere MQ (MQ series), –Oracle Advaced Queueing (AQ) –Microsoft’s MSMQ –Sun’s Java API: Java Message Service (JMS) since 2005 –Amazon’s Simple Queue Service for building automated workflow (aws.amazon.com/sqs)
60
© C. Xu, 1998-2011 MOM (Cont’) u Msgs are forwarded over comm servers and eventually delivered to dest, even if it was down when the msg was sent. u Each app has its own queue and a queue can be read only by its assoc. app. u Multiple apps can share a single queue u Guaranteed that a msg will eventually be inserted in the recipient’s queue, but no guarantee about when, or if the msg will actually be read. –Immediate-term storage capacity for messages u Messaging domain: –Point-to-point vs publish/subscribe
61
© C. Xu, 1998-2011 General Architecture: u Source Queue, Destination Queue, or 3rd-party messaging service (Amazon) u Mapping of queue-level addressing to network-level addressing. (analogous to DNS in email system) u Queue manager u Special manager working as routers: forward msg between queue managers
62
© C. Xu, 1998-2011 Queue Manager, Router, and Overlay Network 2-29 Static vs dynamic routing with routers Multicasting with routers
63
© C. Xu, 1998-2011 Message Brokers (e.g. Amazon’s SQS u Integration of legend applications with new ones to form a single coherent distributed information system u Message broker acts as an appl-level gateway to convert incoming msg to a format that can be understood by the dest app. u The general organization of a message broker in a msg-queuing system.
64
© C. Xu, 1998-2011 Amazon Simple Queue Service u Amazon’s SQS offers a reliable, highly scalable, hosted queue for storing messages as they travel between computers. (aws.amazon.com/sqs) u By using Amazon SQS, developers can simply move data between distributed components of their applications that perform different tasks, without losing messages or requiring each component to be always available. u Make it easy to build an automated workflow u Pricing: $0.01 for 10K SQS requests.
65
© C. Xu, 1998-2011 Basic Queue Requests u CreateQueue: Create queues for use with your AWS account. u ListQueues: List your existing queues. u DeleteQueue: Delete one of your queues. u SendMessage: Add any data entries to a specified queue. u ReceiveMessage: Return one or more messages from a specified queue. u DeleteMessage: Remove a previously received message from a specified queue. u SetQueueAttributes: Control queue settings like the amount of time that messages are locked after being read so they cannot be read again. u GetQueueAttributes: See information about a queue like the number of messages in it.
66
© C. Xu, 1998-2011 Example: IBM WebSphere MQ u Launched in 1992, previously known as MQ series u De-facto standard for messaging across platforms u Queue Manager: handles storage, timing issues, triggering, and all other functions not directly actual movement of data u QM comm with outside via local Binding, or remote Client connection
67
© C. Xu, 1998-2011 Message Channels u MC is a unidirectional, reliable connection between a sending and a receiving queue manager u Each end is managed by a Message Channel Agent (MCA) –check send queue, wrap messages into transport-level packets, send to associated receiving MCA –listening for incoming packets, unwrap them, store into queues AttributeDescription Transport typeDetermines the transport protocol to be used FIFO deliveryIndicates that messages are to be delivered in the order they are sent Message lengthMaximum length of a single message Setup retry count Specifies maximum number of retries to start up the remote MCA Delivery retriesMaximum times MCA will try to put received message into queue
68
© C. Xu, 1998-2011 Message Transfer u Address: queue manager + destination queue; u Each queue manager has a system-wide unique id; Local aliases for queue manager names u Routing tables: (Dest, SendQueue) u Transfer along a channel can take place only if both MCAs are up and runing
69
© C. Xu, 1998-2011 Message Queue Interface u Primitives available in an MQSeries MQI PrimitiveDescription MQopenOpen a (possibly remote) queue MQcloseClose a queue MQputPut a message into an opened queue MQgetGet a message from a (local) queue MQSerie also provides facilities to signal applications when msgs arrive. For more info, see http://www.redbooks.ibm.com/abstracts/sg247128.html
70
© C. Xu, 1998-2011 Messaging Domain u Point-to-Point u Publish/Subscribe –Clients address messages to a topic
71
© C. Xu, 1998-2011 Publish/Subscribe Messaging u Request/Reply (RPC, MRI) model has limitations in two types of applications –Update of state info that changes over time »Send requests regularly for update of the new info. NOT efficient –Action in response to event occurrence: »Send event info to ALL nodes who are interested in u Publish/Subscribe messaging –Any number of customers of info can receive messages that are provided by one or more producers of the info –Publisher: producer of the info –Subscriber: consumer of the info –Topic (or named logical channel) to be subscribed by consumers to register their interests –Publish/subscribe broker: track subscriptions to individual topics and provide facilitates for a publisher to publish msgs on a given topic u Topic-based vs content-based vs hybrid systems
72
© C. Xu, 1998-2011 JMS Programming u Available in Java System Message Queue V3.6 u Interfaces: –ConnectionFactory »Administrated object used to create a connection to JMS provider »Defined by administrator, rather than programmer –Connection »A conn represents a comm link between app and msg server »Administrated object –Destination: where msg is delivered and consumed »Queue or topic –MessageConsumer –MessageProducer –Message –Session: Single threaded context for sending and receiving messages u http://www.sun.com/software/products/message_queue/index.xml
73
© C. Xu, 1998-2011 JMS Programming Model
74
© C. Xu, 1998-2011 Producer (1/3) injects resources for a connection factory, queue, and topic : @Resource(mappedName="jms/ConnectionFactory") private static ConnectionFactory connectionFactory; @Resource(mappedName="jms/Queue") private static Queue queue; @Resource(mappedName="jms/Topic") private static Topic topic; Assigns either the queue or topic to a destination object, based on dest type : Destination dest = null; try { if (destType.equals("queue")) { dest = (Destination) queue; } else { dest = (Destination) topic; } } catch (Exception e) {}
75
© C. Xu, 1998-2011 Producer (2/3) Creates a Connection and a Session: Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Creates a MessageProducer and a TextMessage: MessageProducer producer = session.createProducer(dest); TextMessage message = session.createTextMessage(); Sends one or more messages to the destination: for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); System.out.println("Sending message: " + message.getText()); producer.send(message); }
76
© C. Xu, 1998-2011 Producer (3/3) Sends an empty control message to indicate the end of the message stream: producer.send(session.createMessage()); Sending an empty message of no specified type is a convenient way to indicate to the consumer that the final message has arrived. Closes the connection in a finally block, automatically closing the session and MessageProducer: } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } }
77
© C. Xu, 1998-2011 Async Consumer 1. injects resources for a connection factory, queue, and topic. 2. Assigns either the queue or topic to a destination object, based on the specified dest type. 3. Creates a Connection and a Session. 4. Creates a MessageConsumer. 5. Creates an instance of the TextListener class and registers it as the message listener for the MessageConsumer: listener = new TextListener(); consumer.setMessageListener(listener); 6. Starts the connection, causing message delivery to begin. 7. Listens for the messages published to the destination, stopping when the user types the character q or Q: System.out.println("To end program, type Q or q, " + "then "); inputStreamReader = new InputStreamReader(System.in); while (!((answer == 'q') || (answer == 'Q'))) { try { answer = (char) inputStreamReader.read(); } catch (IOException e) { } } 8. Closes the connection, which automatically closes the session and MessageConsumer.
78
© C. Xu, 1998-2011 Async Consumer (2/2) When a message arrives, the onMessage method is called automatically. The onMessage method converts the incoming message to a TextMessage and displays its content. If the message is not a text message, it reports this fact: public void onMessage(Message message) { TextMessage msg = null; try { if (message instanceof TextMessage) { msg = (TextMessage) message; System.out.println("Reading message: " + msg.getText()); } else { System.out.println("Message is not a " + "TextMessage"); } } catch (JMSException e) } catch (Throwable t) { } }
79
© C. Xu, 1998-2011 Email vs Message Queue u Email is a special case of Message Queue –Email aims at providing direct support for end users –Email makes direct use of the underlying transport services (SMTP over TCP); routing is left out u General MQ can satisfy a different set of requirements: » guaranteed message delivery, »message priorities, »logging facilities, »efficient multicasting, »load balancing, »fault tolerance, etc.
80
© C. Xu, 1998-2011 Comm in DS: In Summary Communication Point-to-pointMulticast group comm Two-way comm One-way comm Socket prog RPC/RMI Message-oriented
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.