Distribution And Integration Technologies

Transcription

Distribution and IntegrationTechnologiesComponent ServicesQueues and transactionsQueues and transactions1

Queues and messages Allows the transmission of messages of any type Reliable transmission We can have persistence at the source and destination sides We can send even if the destination is not available at themoment (MSMQ) Send and receive operations can be included in transactionsScenario with distributed queues (private MSMQ)Sendoutgoingqueuedestinationqueueapp 1Receiveapp 2Queue ServerQueue ServerQueues and transactions2

Queues and messages (.NET) Use the OS service named MSMQ through a .NET class outgoing queues (automatic for outgoing messages)public queues (only on Windows domains)private queues (can be created in any Windows system). . . (others) Friendly names: [machine]\[queue](public)or[machine]\private \[queue] (private) Local: .\[queue] or .\private \[queue] Direct: FormatName:DIRECT TCP:x.x.x.x\private \[queue]FormatName:DIRECT OS:[machine]\private \[queue] These direct names allow offline sends and receives .NET classes for working with queues and messages MessageQueue MessageQueues and transactions3

QueuesUse of the MSMQ service in .NETQueue object linked with a queue: MessageQueue q new MessageQueue(“name”);Free queue object: MessageQueue q new MessageQueue();Creation of a queue (static method Create( ))q MessageQueue.Create(“name”);Test if a queue is already created (static method Exists( )):if (MessageQueue.Exists(“name”)) . . .List the private queues of a machine:MessageQueue[ ] qs;qs ��);foreach (MessageQueue q in qs)Console.WriteLine(q.Path);Send a message:MessageQueue q new MessageQueue(@”.\private \testqueue”);q.Formatter new BinaryMessageFormatter( ); //default: XmlMessageFormatterq.Send(anyobject, “Title”);Queues and transactions4

Queues – synchronous receiveReceive a messageMessageQueue q new MessageQueue(@”.\private \testqueue”);q.Formatter new BinaryMessageFormatter();// if the object we want to receive is not from the Framework we need a [Serializable] shared class// in the case of an XML formatter, we must specify the allowed types Example:// Type[ ] allowed new Type[ ] {typeof(anytype1), typeof(anytype2), . . . };// q.Formatter new XmlMessageFormatter(allowed);Message m;while (true) {m q.Receive(TimeSpan.FromSeconds(60));if (m null) {.if reak;}else {.(anytype) m.Body.}}Queues and transactions// we can specify a timeout5

Queues – asynchronous receiveReceive a message when it arrivesMessageQueue mq new MessageQueue(@”.\private \testqueue”);mq.Formatter new BinaryMessageFormatter();mq.ReceiveCompleted QueueReceiver;mq.BeginReceive(); private void QueueReceiver(object src, ReceiveCompletedEventArgs rcea) {System.Messaging.Message msg mq.EndReceive(rcea.AsyncResult);// if we don’t have access to the mq object, the parameter src is a copy . (anytype) msg.Body .mq.BeginReceive();// if we need to receive another message}Queues and transactions6

Queued components Remote objects can use queues as a transport protocol Transparent to the programmer (object executes a normal call)The called method must be oneway (returns void)Technologies: COM and now WCF (in Windows)MDB’s (Message Driven Beans in JavaEE)createscallapp istenermMSMQMSMQCalling a remote method asynchronouslyQueues and transactionsplayercallremoteobject7

Queues in Java Uses a standard specification – JMS (in JavaEE) JMS – Java Messaging Service Several providers implement standalone JMS servers IBM MQ Series, Apache ActiveMQ, Almost every JavaEE Application Server contains a JMS servermsgmsgQueue providerConsumerProducersendsreceivesqueue In this centralized mode the server must be alwaysavailableQueues and transactions8

JMS in Application Servers Queues and ConnectionFactories are server resources They can be created administratively They can be used in Application Clients by resourceinjection (through the annotation - @Resource())Application ServerRich clientapplicationClient app containerothercontainersJMSMessageQueuesRich clientapplicationresourcesClient app containerQueues and transactions9

JMS structural architectureQueues and transactions10

Send a JMS messagepublic class Sender {@Resource (mappedName "jms/Order")private static Queue queue;@Resource (mappedName "jms/ defaultConnectionFactory")private static ConnectionFactory queueFactory;public static void main(String[ ] args) {// Creates the needed artifacts to connect to the queueConnection connection queueFactory.createConnection();Session session connection.createSession(false, Session.AUTO ACKNOWLEDGE);MessageProducer producer session.createProducer(queue);// Sends a text message to the queueTextMessage message session.createTextMessage();message.setText("This is a text );}}Queues and transactions11

Receive a JMS messagepublic class Receiver {@Resource (mappedName "jms/Order")private static Queue queue;@Resource (mappedName "jms/ / defaultConnectionFactory")private static ConnectionFactory queueFactory;public static void main(String[ ] args) {// Creates the needed artifacts to connect to the queueConnection connection queueFactory.createConnection();Session session connection.createSession(false, Session.AUTO ACKNOWLEDGE);MessageConsumer consumer / Loops to receive the messageswhile (true) {TextMessage message (TextMessage) consumer.receive();System.out.println("Message received: " message.getText());}}}Queues and transactions12

Receiving asynchronouslypublic class Listener implements MessageListener {@Resource(mappedName "jms/queueFactory")private static ConnectionFactory connectionFactory;@Resource(mappedName "jms/queue")private static Queue queue;public static void main(String[ ] args) {// Creates the needed artifacts to connect to the queueConnection connection connectionFactory.createConnection();Session session connection.createSession(false, Session.AUTO ACKNOWLEDGE);MessageConsumer consumer istener(new Listener());connection.start();}public void onMessage(Message message) {System.out.println("Message received: " ((TextMessage) message).getText());}}Queues and transactions13

Transactions Local transactions Involving a single DBMS or other transactional resources(resources that have a CRM – Compensating Resource Manager) Distributed transactions Involve resources in several machines (or servers) Also there is the involvement of several services: A Transaction Manager in each machine A CRM in each tansaction supporting resourceQueues and transactions14

Transaction properties ACID properties A – Atomicity – The global operation succeeds or fails as a all C – Consistency – The resources start and end always in aconsistent state regarding the data involved in the operation I – Isolation – possible intermediate inconsistent states are notvisible by other concurrent operations. They must see alwaysconsistent states, either the one existing before or after thetransactional operation D – Durability – when the transaction is announced as finishedthe data must be in a persistent state capable of surviving alogic crash or power lossQueues and transactions15

Local transactions Must be, whenever possible, implemented at the level ofresource manager For instance in DBMS’s we should use “stored procedures” ifthey suport them Example:BEGIN TRANSACTION. . . SQL statements.IF (@@ERROR 0)ROLLBACK TRANSACTIONELSECOMMIT TRANSACTIONEND TRANSACTIONQueues and transactions16

Local Transactions We can also implement them at the level of ourFramework API (.NET, Java, etc) Example in ADO.NETPreparationcon.Open();SqlTransaction tr con.BeginTransaction();.cmdA.Transaction tr;cmdB.Transaction tr;.Queues and transactionstry .commit();}catch (Exception e) {.tr.rollback();}finally {con.Close();}17

Distributed TransactionsTr. SubordinateTwo-phase commit protocol[Supported]DTCClientcreateTr. CoordinatorCRM[Required]Tr. rceabort/commit ?Tr. Subordinatedecisionrollback/commitDTC – Distributed Transaction Coordinator[Supported]voteCRM – Compensating Resource ManagerQueues and transactionsDTCCRMresource18

Queues and messages Allows the transmission of messages of any type Reliable transmission We can have persistence at the source and destination sides We can send even if the destination is not available at the moment (MSMQ) Send and receive operations can be included in transactions Queues and transactions 2 app 2 Send outgoing queue Queue Server Queue Server