df5578f6873861ee8bc48f3ee86a83e2.ppt
- Количество слайдов: 78
Communication in Distributed Systems Cheng-Zhong Xu
Taxonomy Communication Point-to-point Two-way comm Socket prog Multicast group comm One-way comm RPC/RMI Message-oriented © 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 © 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 © 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!! © 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 arguments – server computes – Server sends back reply data u Implementation of the procedures or methods are on remote servers © C. Xu, 1998 -2011
Conventional Procedure Call For example, count = read(fd, buf, nbytes); a) b) Parameter passing in a local procedure call: the stack before the call to read The stack while the called procedure is active © 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 u The mechanism automates the writing of data-handling and formatting code Advantages: fewer errors, faster to code and evolve interfaces © C. Xu, 1998 -2011
RPC Structure: Client/Server Proxies (stub, skeleton) client program server program call return client stub call server skeleton network 1. 2. 3. 4. 5. 6. Client procedure calls client stub in normal way Client stub builds message, calls local OS Client's OS sends message to remote OS Remote OS gives message to server stub/skel Server stub unpacks parameters, calls server Server does work, returns result to the stub 7. 8. 9. 10. Server stub packs it in message, calls local OS Server's OS sends message to client's OS Client's OS gives message to client stub Stub unpacks result, returns to client © C. Xu, 1998 -2011
Passing Parameters u Steps involved in doing remote computation through RPC 2 -8 © 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 © 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 u Distributed objects have a separation between interfaces and objects that implement the interfaces; interfaces and the objects are in different machines. 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 © C. Xu, 1998 -2011
Organization of Distributed Objects u u Separate proxy for each remote object that is referenced 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 © 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 © 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 u use table to maintain one-to-one mapping from proxy object to remote object interactions with garbage collection © C. Xu, 1998 -2011
Building an RMI App server interface client code client stub generator server impl server skeleton compiler/ linker client app server app Server code © 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 © C. Xu, 1998 -2011
Interface Definition u All remote objects are referenced through interfaces – It extends the Remote interface as all RMI interfaces must – Methods must throw Remote. Exception import java. rmi. *; public interface my. Server extends Remote { public void do. Something( … ) throws Remote. Exception; } © C. Xu, 1998 -2011
// my. Client // my. Server object has registered itself as “xu. Object” import java. rmi. *; import java. rmi. server. *; public class my. Client { public static void main( String[] args ) { System. set. Security. Manager( new RMISecurity. Manager() ); try { my. Server ro= (my. Server)Naming. lookup(“xu. Object”); ro. do. Something(); } catch (Exception e) {} } } © 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 © C. Xu, 1998 -2011
// my. Server implementation import java. rmi. *; import java. rmi. server. *; import java. rmi. registry. *; public class my. Server. Impl extends Unicast. Remote. Object implements my. Server { public my. Server. Impl() throws Remote. Exception{ } public void do. Something(… ) throws Remote. Exception{… …} public static void main( String[] args) { System. set. Security. Manager( new RMISecurity. Manager()); try { my. Server. Impl obj = new my. Server. Impl(); Naming. rebind(“xu. Object”, obj); System. out. println(“do. Something bound in registry”); }catch (Exception e) {} } © C. Xu, 1998 -2011 }
Notes u my. Server. Impl extends – java. rmi. server. Unicast. Remote. Object class, which defines a non-replicated remote object whose references are valid only while the my. Server 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 © C. Xu, 1998 -2011
Deployment u Generate stub and skeleton – rmic my. Server. Impl, which generates » my. Server. Impl_Stub. class, my. Server. Impl_Skel. class – Since JDK 5. 0, stub classes can be generated ondemand at runtime u rmiregistry – starts the registry service in the background u java Server. Impl – starts the server, which registers the remote object with the registry u java Client © 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 Remote. Object – remote object refers to an object whose method can be invoked from another JVM. – Remote objects passed by reference, while nonremote objects passed by copy u A difference between RPC and RMI – passing objects, – passed object may interact with receipt itself © 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: O 1 in machine A and O 2 in machine B © C. Xu, 1998 -2011
Passing objects u Object Serialization – To be passed between client/server, objects have to be serialized u For example, – Cloud. Server, which do jobs for clients in clouds – Different clients may ask Cloud. Server do different jobs – Each job is specified in arguments passed from a client to the server © 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 ); } } © C. Xu, 1998 -2011
// Cloud. Server. java import java. rmi. *; import java. util. *; public interface Cloud. Server extends Remote { Object execute( Task o) throws Remote. Exception } © C. Xu, 1998 -2011
// Cloud. Server. Impl. java import java. rmi. *; import java. io. *; import java. rmi. server. *; public class Cloud. Server. Impl implements Cloud. Server { public Cloud. Server. Impl() throws Remote. Exception{} public Object execute( Task t) throws Remote. Exception { return t. execute(); } public static void main (String args[]) { System. set. Security. Manager( new RMISecurity. Manager()); try { Cloud. Server csr = new Cloud. Server. Impl(); Naming. rebind(“Cloud. Server”, csr); } catch (IOException ioe) {} © 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 Remote. Exception { System. set. Security. Manager( … ); new example(args[0]); } public example( String host ) { try { Cloud. Server csr = (Cloud. Server) Naming. lookup(“rmi: //”+host+“/Cloud. Server”); System. out. println( csr. execute( new foo(10) ); catch (IOException ioe) {} © C. Xu, 1998 -2011
Running on different machines u Server site – – – Cloud. Server. class Cloud. Server. Impl_Stub. class Cloud. Server. Impl_Skel. class Task. class u Client site – – – Cloud. Server. class example. class Cloud. Server. Impl_Stub. class Task. class foo. class u java Cloud. Server. Impl At client site java -Djava. rmi. server. codebase=‘…’ example server © C. Xu, 1998 -2011
Remote Object References u Asynchronous Client/Server Comm – Client calls Cloud. Server’s asyn. Execute(…) – On the completion of the work, the Cloud. Server notifies the client of the result u Client itself is declared as a Remote Object, which reference is passed to Cloud. Server u Cloud. Server calls work. Completed(…) of the remote object. © C. Xu, 1998 -2011
// Cloud. Server. java import java. rmi. *; import java. util. *; public interface Cloud. Server extends Remote { Object execute( Task work ) throws Remote. Exception void asyn. Execute( Task work, Work. Listener listener) throws Remote. Exception } © C. Xu, 1998 -2011
Public class Cloud. Server. Impl extends Unicast. Remote. Object implements Cloud. Server { … … public void asyn. Execute(Task work, Work. Listener listener) throws Remote. Exception { Object result = work. execute(); listener. work. Completed( work, result ); } } © C. Xu, 1998 -2011
Work. Listener Remote Interface // Work. Listener. java public interface Work. Listener extends Remote { public void work. Completed( Task request, Object result ) throws Remote. Exception; } Example. java will be modified to implement the remote interface. This turns example into a remote object © C. Xu, 1998 -2011
import java. rmi. *; import java. io. *; public class example extends Unicast. Remote. Object implements Work. Listener { public static void main( ) throws Remote. Exception {…} public void work. Completed( Task t, Object result) throws Remote. Exception { System. out. println(“Async work result = “ + result); } public example ( String host ) throws Remote. Exception { try { Cloud. Server csr = (Cloud. Server) Naming. lookup(“rmi: //”+host+“/Cloud. Server”); csr. asyn. Execute( new foo(10), this ); catch (IOException ioe) {} } © C. Xu, 1998 -2011
Remarks u Asynchronous RPC: A client and server interacting through two asynchronous RPCs Asynchronous RMI ? ? © 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 © 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 © C. Xu, 1998 -2011
Naplet: A mobile object middleware system u Structured Itinerary Mechanism – Sequential/parallel/alternative visit of a group of servers u u Naplet directory based location + Forward Pointer Message-oriented communication Persistent comm between mobile objects Un/secure execution – Multithreaded objects – Secure access to local resource u Java based Naplet 0. 2 source code available http: //www. ece. eng. wayne. edu/~czxu/ software/naplet. html © C. Xu, 1998 -2011
Taxonomy Communication Point-to-point Two-way comm Socket prog Multicast group comm One-way comm RPC/RMI Message-oriented © C. Xu, 1998 -2011
Message-Oriented Persistent Communication © C. Xu, 1998 -2011
Organization of Comm System Examples: Email --- Client/Outbound Mail Server/Inbound Server MPI --- Message Passing Layer © C. Xu, 1998 -2011 Difference? ?
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 © 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. © 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 )© C. Xu, 1998 -2011
2 -22. 2 c) d) Transient asynchronous communication (e. g. UDP, asynchronous RPC). Transmission fails if the receiver is not executing at the time the msg arrives. Receipt-based transient synchronous communication. Sender is blocked until the msg is stored in a local buffer at the receiving host. (Example? ) © C. Xu, 1998 -2011
e) f) Delivery-based transient synchronous communication at message delivery. (Sender is blocked until the msg is delivered to the receiver) Response-based transient synchronous communication (e. g. RPC and RMI) (Sender is blocked until it receives a reply msg from the receiver) © 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 © C. Xu, 1998 -2011 – But, persistent comm. incurs long delays
Message-Oriented Transient Comm. u u Socket is a communication endpoint to which an appl can write data to and from which incoming data can be read Socket primitives for TCP/IP. Primitive Meaning Socket Create a new communication endpoint Bind Attach a local address to a socket Listen Announce willingness to accept connections Accept Block caller until a connection request arrives Connect Actively attempt to establish a connection Send some data over the connection Receive some data over the connection Close Release the connection © C. Xu, 1998 -2011
Berkeley Sockets u Connection-oriented communication pattern using sockets. © C. Xu, 1998 -2011
MPI: Another Transient Comm u Basic message-passing primitives of MPI. Primitive Meaning MPI_bsend Append outgoing message to a local send buffer of MPI runtime MPI_send Send a message and wait until copied to local or remote buffer MPI_ssend Send a message and wait until receipt starts MPI_sendrecv Send a message and wait for reply MPI_isend Pass reference to outgoing message, and continue MPI_issend Pass reference to outgoing message, and wait until receipt starts MPI_recv Receive a message; block if there are none MPI_irecv Check if there is an incoming message, but do not block © 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 © 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. © C. Xu, 1998 -2011
MQ Model 2 -26 u Four combinations for loosely-coupled comm. using queues (sender and receiver can execute completely independently of each other) © C. Xu, 1998 -2011
MQ: Interface to a Queue One-way Communication Primitives: Primitive Meaning Put Append a message to a specified queue (non-blocking) Get Block until the specified queue is nonempty, and remove the first message Poll Check 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. • 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? © 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 Web. Sphere 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 © C. Xu, 1998 -2011 workflow (aws. amazon. com/sqs)
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 © C. Xu, 1998 -2011
General Architecture: u Source Queue, Destination Queue, or 3 rd-party messaging service (Amazon) Mapping of queue-level addressing to network-level addressing. (analogous to DNS in email system) Queue manager u Special manager working as routers: forward msg between queue managers u u © C. Xu, 1998 -2011
Queue Manager, Router, and Overlay Network 2 -29 • Static vs dynamic routing with routers • Multicasting with routers © C. Xu, 1998 -2011
Message Brokers (e. g. Amazon’s SQS u u u Integration of legend applications with new ones to form a single coherent distributed information system Message broker acts as an appl-level gateway to convert incoming msg to a format that can be understood by the dest app. The general organization of a message broker in a msg-queuing system. © 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 10 K SQS requests. © C. Xu, 1998 -2011
Basic Queue Requests u u u u Create. Queue: Create queues for use with your AWS account. List. Queues: List your existing queues. Delete. Queue: Delete one of your queues. Send. Message: Add any data entries to a specified queue. Receive. Message: Return one or more messages from a specified queue. Delete. Message: Remove a previously received message from a specified queue. Set. Queue. Attributes: Control queue settings like the amount of time that messages are locked after being read so they cannot be read again. Get. Queue. Attributes: See information about a queue like the number of messages in it. © C. Xu, 1998 -2011
Example: IBM Web. Sphere MQ u u Launched in 1992, previously known as MQ series De-facto standard for messaging across platforms Queue Manager: handles storage, timing issues, triggering, and all other functions not directly actual movement of data QM comm with outside via local Binding, or remote Client connection © C. Xu, 1998 -2011
Message Channels u u MC is a unidirectional, reliable connection between a sending and a receiving queue manager 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 Attribute Description Transport type Determines the transport protocol to be used FIFO delivery Indicates that messages are to be delivered in the order they are sent Message length Maximum length of a single message Setup retry count Specifies maximum number of retries to start up the remote MCA Delivery retries Maximum times MCA will try to put received message into queue © C. Xu, 1998 -2011
Message Transfer u u Address: queue manager + destination queue; Each queue manager has a system-wide unique id; Local aliases for queue manager names Routing tables: (Dest, Send. Queue) Transfer along a channel can take place only if both MCAs are up and runing © C. Xu, 1998 -2011
Message Queue Interface u Primitives available in an MQSeries MQI Primitive Description MQopen Open a (possibly remote) queue MQclose Close a queue MQput Put a message into an opened queue MQget Get 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/sg 247128. html © C. Xu, 1998 -2011
Messaging Domain u Point-to-Point u Publish/Subscribe – Clients address messages to a topic © 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 © C. Xu, 1998 -2011
JMS Programming u u Available in Java System Message Queue V 3. 6 Interfaces: – Connection. Factory » 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 – – u Message. Consumer Message. Producer Message Session: Single threaded context for sending and receiving messages http: //www. sun. com/software/products/message_queue/index. xml © C. Xu, 1998 -2011
JMS Programming Model © C. Xu, 1998 -2011
Producer (1/3) injects resources for a connection factory, queue, and topic: @Resource(mapped. Name="jms/Connection. Factory") private static Connection. Factory connection. Factory; @Resource(mapped. Name="jms/Queue") private static Queue queue; @Resource(mapped. Name="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 (dest. Type. equals("queue")) { dest = (Destination) queue; } else { dest = (Destination) topic; } © C. Xu, 1998 -2011 } catch (Exception e) {}
Producer (2/3) Creates a Connection and a Session: Connection connection = connection. Factory. create. Connection(); Session session = connection. create. Session(false, Session. AUTO_ACKNOWLEDGE); Creates a Message. Producer and a Text. Message: Message. Producer producer = session. create. Producer(dest); Text. Message message = session. create. Text. Message(); Sends one or more messages to the destination: for (int i = 0; i < NUM_MSGS; i++) { message. set. Text("This is message " + (i + 1)); System. out. println("Sending message: " + message. get. Text()); producer. send(message); } © C. Xu, 1998 -2011
Producer (3/3) Sends an empty control message to indicate the end of the message stream: producer. send(session. create. Message()); 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 Message. Producer: } finally { if (connection != null) { try { connection. close(); } catch (JMSException e) { } } } © 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 Message. Consumer. 5. Creates an instance of the Text. Listener class and registers it as the message listener for the Message. Consumer: listener = new Text. Listener(); consumer. set. Message. Listener(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 <return>"); input. Stream. Reader = new Input. Stream. Reader(System. in); while (!((answer == 'q') || (answer == 'Q'))) { try { answer = (char) input. Stream. Reader. read(); } catch (IOException e) { } } 8. Closes the connection, which automatically closes the session and Message. Consumer. © C. Xu, 1998 -2011
Async Consumer (2/2) When a message arrives, the on. Message method is called automatically. The on. Message method converts the incoming message to a Text. Message and displays its content. If the message is not a text message, it reports this fact: public void on. Message(Message message) { Text. Message msg = null; try { if (message instanceof Text. Message) { msg = (Text. Message) message; System. out. println("Reading message: " + msg. get. Text()); } else { System. out. println("Message is not a " + "Text. Message"); } } catch (JMSException e) } catch (Throwable t) { } © 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. © C. Xu, 1998 -2011
Comm in DS: In Summary Communication Point-to-point Two-way comm Socket prog Multicast group comm One-way comm RPC/RMI Message-oriented © C. Xu, 1998 -2011
df5578f6873861ee8bc48f3ee86a83e2.ppt