RabbitMQ guide utilisateur du client .NET version 1.5.0
54 pages
English

RabbitMQ guide utilisateur du client .NET version 1.5.0

Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres
54 pages
English
Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres

Description

Vue d'ensemble de l'implémentation du client .NET pour RabbitMQ

Sujets

Informations

Publié par
Publié le 13 décembre 2013
Nombre de lectures 321
Licence : En savoir +
Paternité, pas d'utilisation commerciale, partage des conditions initiales à l'identique
Langue English

Extrait

RabbitMQ .NET Client Library User Guide
Copyright © 2007, 2008, 2009 LShift Ltd. Cohesive Financial Technologies LLC. Rabbit Technologies Ltd.
Table
of Contents
1. UserGuide ...............................................................................................................................................4
1.1. Introduction .................................................................................................................................4 1.2. AMQP dialects implemented ......................................................................................................4
2. ApiOverview...........................................................................................................................................4
2.1. Major namespaces, interfaces and classes ..................................................................................4 2.2. Multi-protocol support ................................................................................................................5 2.3. Connecting to a broker ................................................................................................................6 2.4. Disconnecting from a broker.......................................................................................................7 2.5. Using exchanges and queues.......................................................................................................7 2.6. Publishing messages ...................................................................................................................8 2.7. Retrieving individual messages...................................................................................................8 2.8. Retrieving messages by subscription ..........................................................................................9 2.9. Threading, deadlocks, and associated restrictions on consumers .............................................10 2.10. IModel should not be shared between threads ........................................................................11 2.11. Handling unroutable or undelivered messages........................................................................11 2.12. QPid-compatible JMS BytesMessage, StreamMessage, and MapMessage codecs................12
3. MessagingPatterns ...............................................................................................................................13
3.1. Common ways of working with AMQP ...................................................................................13 3.2. Point-to-point messaging ..........................................................................................................13 3.2.1. Synchronous, client-server remote procedure call (RPC) ............................................13 3.2.2. Asynchronous, one-way messaging .............................................................................15 3.2.3. Acknowledgment modes for point-to-point .................................................................16 3.2.4. Library support for point-to-point messaging ..............................................................16 3.3. Event broadcasting ....................................................................................................................18 3.3.1. Publishing events ..........................................................................................................19 3.3.2. Subscription ..................................................................................................................19 3.3.3. Retrieving events - low-level approach ........................................................................20 3.3.4. Acknowledgment modes for event broadcasting..........................................................20 3.4. Responsibility transfer ..............................................................................................................21 3.5. Reliable message transfer..........................................................................................................22 3.5.1. At-least-once delivery...................................................................................................22 3.5.2. At-most-once delivery ..................................................................................................23 3.5.3. Exactly-once delivery ...................................................................................................23 3.6. Coding with high-availability AMQP server pairs....................................................................24 3.7. Interacting with external resources ...........................................................................................24
4. ShutdownProtocols ..............................................................................................................................25
4.1. General pattern of AMQP client shutdown...............................................................................25 4.2. Information about the circumstances of a shutdown.................................................................26 4.2.1. ShutdownInitiator .........................................................................................................26 4.2.2. ShutdownEventArgs .....................................................................................................26 4.3. The CloseReason properties, and idempotency of Close() calls...............................................27 4.4. Atomicity, and use of the IsOpen flags .....................................................................................27 4.5. Specific shutdown protocols .....................................................................................................28 4.5.1. IModel ..........................................................................................................................28 4.5.2. IConnection ..................................................................................................................28 4.5.3. ISession.........................................................................................................................29
5. TroubleShooting...................................................................................................................................29
5.1. Heartbeat issue with Mono 1.1.17.1 on Redhat FC6/x86-64....................................................29
6. Examples...............................................................................................................................................30
6.1. How to run examples.................................................................................................................30 6.2. Examples overview ...................................................................................................................30 6.2.1. AddClient .....................................................................................................................30 6.2.2. AddServer .....................................................................................................................30 6.2.3. DeclareQueue ...............................................................................................................30 6.2.4. ExceptionTest ...............................................................................................................31 6.2.5. LogTail..........................................................................................................................31 6.2.6. SendMap.......................................................................................................................31 6.2.7. SendString ....................................................................................................................31 6.2.8. SingleGet ......................................................................................................................31
7. BuildingTheClient................................................................................................................................31
7.1. Source Tree Layout ...................................................................................................................32 7.2. Build Prerequisites ....................................................................................................................33 7.3. Configuring Your Tree ..............................................................................................................34 7.4. Available Build Targets .............................................................................................................34 7.4.1. clean..............................................................................................................................34 7.4.2. build (default) ...............................................................................................................34 7.4.3. doc ................................................................................................................................34 7.4.4. examples .......................................................................................................................34 7.4.5. unit ................................................................................................................................35 7.4.6. stamp.............................................................................................................................35 7.5. Build Products...........................................................................................................................35 7.6. Assembly Versioning ................................................................................................................35
8. BuildingTheWcfBinding .....................................................................................................................36
8.1. Build Prerequisites ....................................................................................................................36 8.2. Building with NAnt ...................................................................................................................36 8.2.1. clean-wcf ......................................................................................................................37 8.2.2. build-wcf.......................................................................................................................37 8.2.3. wcf-examples................................................................................................................37 8.3. Build Products...........................................................................................................................37
9. ImplementationGuide..........................................................................................................................37
9.1. Connections, Channels, Sessions and Models ..........................................................................37 9.2. Channel zero .............................................................................................................................38 9.3. Information dataflow from the server to the client....................................................................38 9.4. Information dataflow from the client to the server....................................................................40 9.5. Client-to-server AMQP RPC ....................................................................................................40 9.6. Constants from the specification ...............................................................................................41
10. ApiGen ................................................................................................................................................41
10.1. Compilation Process Overview ...............................................................................................42 10.2. Invoking Apigen......................................................................................................................43 10.3. Generated Classes ...................................................................................................................43 10.4. The Common Model ...............................................................................................................47 10.4.1. The main model interface ...........................................................................................47 10.4.2. Content header interfaces ...........................................................................................47 10.4.3. Mapping methods to RPC requests ............................................................................48 10.4.4. Mapping method parameters to RPC request fields ...................................................49 10.4.5. Mapping RPC responses to return values...................................................................51 10.4.6. Mapping asynchronous events....................................................................................52 10.4.7. Overriding behaviour for particular specification versions ........................................53
1. UserGuide
1.1. Introduction
The RabbitMQ .NET client is an implementation of an AMQP client library for C# (and, implicitly, other .NET languages), and a binding exposing AMQP services via Microsoft’s Windows Communication Foundation (WCF).
This is the User Guide for the RabbitMQ .NET client library. It provides an overview of the codebase and the implemented API.
The full details of the API are documented separately, in the NDocProc-generated javadoc-like HTML documentation.
1.2. AMQP dialects implemented
The client library implements AMQP specifications version 0-8, 0-8bis (0-8 as modified by QPid for their M2 release) and 0-9 (omitting sections of the specification marked "work in progress", i.e. the Messagecontent-class). The ApiGen tool processes the specification XML files in conjunction with certain C# interfaces, generating C# code directly, which is compiled into the final assembly.
2. ApiOverview
This section gives an overview of the RabbitMQ .NET client API.
Only the basics of using the library are covered: for full detail, please see the javadoc-like API documentation generated from the source code.
2.1. Major namespaces, interfaces and classes
The API is closely modelled on the AMQP protocol specification, with little additional abstraction.
The core API interfaces and classes are defined in thetMQ.abbintClieRspmneae:ac
using RabbitMQ.Client;
The core API interfaces and classes are
4
RabbitMQ .NET Client Library User Guide
IModel: represents an AMQP data channel, and provides most of the AMQP operations ICneonoitcn: represents an AMQP connection rycaotoiFnentcCno: constructsCoInoitcenninstances
Other useful interfaces and classes include: aramionPseterentcCno: configures aFaonorctynnoCitce QueieugnaBisCcnousemr: receives messages delivered from the server slocotorP: support class for choosing an AMQP protocol variant
Public namespaces other thanilnetbbitMQ.CRainclude: QMC.bbatRi.toCilnetnten: construction and analysis of messages that are binary-compatible with messages produced and consumed by QPid’s JMS compatibility layer. RabsntE.eveitn.QlCibMt: various events and event handlers that are part of the AMQP client library. MQitli.CbbRaoitpsn.tneecxE: exceptions visible to the user of the AMQP client library.
All other namespaces are reserved for private implementation detail of the library, although members of private namespaces are usually made available to applications using the library in order to permit developers to implement workarounds for faults or design mistakes they discover in the library implementation. Applications cannot rely on any classes, interfaces, member variables etc. that appear within private namespaces remaining stable across releases of the library.
2.2. Multi-protocol support
ClassRQ.tMbiabP.tneilCslocotorcontains convenient predefinedotPrIcoloinstances that permit selection of a supported protocol variant. At the time of writing, the library supports: torPtlualocotoroPef.Dlsco: An alias to one of the other protocols. At the time of writing,the default protocol isAMQP_0_8. tocolo.sMAPQ0_8_Pr: Standard, unmodified AMQP 0-8 protocol, includingeccastueeq.rss. PQ0_8_Q_colo.sMAotPrPID: AMQP 0-8 as extended by QPid’s 0-8 M1 release, without access.requestand with extra parameters available on certain methods. Protocols.AMQP_09_: Standard, unmodified AMQP 0-9 protocol, including.reqcessuestca, but excluding theMessageareas of the specification marked "work in progress".content-class and other
ThesotProlocclass also contains some convenience functions for retrieving an IProtocol from a string, from the environment or from a .NET XML configuration file. The protocol names permitted are the same as the static instance variables on classrPtoscolo, that is,MQA0_P_8,0_PQQ_8_DIPAM, AMQP_0_9, andorotoclDefaultP.
5
RabbitMQ .NET Client Library User Guide
The following code bindspto thelMsQc.oA0t_oPr_oP9instance by looking it up dynamically:
IProtocol p = Protocols.SafeLookup("AMQP_0_9");
Given the followingAgonfipp.csnippet, <appSettings> <add key="my-protocol" value="AMQP_0_ "/> 9 </appSettings>
the following code will also bindpto the 0-9lotocPIorion:ntatelemipm
IProtocol p = Protocols.FromConfiguration("my-protocol");
An alternative isromEnvirtocols.Firbael)(noemtnaVorP, which reads the name of the protocol variant to return from the shell environment variable named byivormnneVtraailbeotPrEns.oloc (at the time of writing,QMARP_PCOTOOL).
Finally,)(tnemnroviEnomFrs.olocotPrtriesmorFn()atioigurConffirst, and if no setting is found, falls back tovnEmnoriorFable()mentVari.
If no argument is passed to()ntmeorFnorivnEmornfCoomFrtaoigiru(n), the value of Protocols.DefaultAppSettingsKeyof writing, the default appSettings key isis used. (At the time AMQP_PROTOCOL, the same as the name of the shell environment variable scanned.)
2.3. Connecting to a broker
The following code connects to an AMQP broker:
ConnectionFactory factory = new ConnectionFactory(); IProtocol protocol = Protocols.FromEnvironment(); IConnection conn = factory.CreateConnection(protocol,
The default parameters are: username:"guest" password:"guest" :ohtsau-lvirt"/"
hostName, portNumber);
For control over the username, password and virtual-host supplied to the broker, modify the ConnectionFactory’ssonCoiPnentctereramaobject before callingitnoCreannecteCo:
ConnectionParameters params = factory.Parameters; params.UserName = userName;
6
RabbitMQ .NET Client Library User Guide
params.Password = password; params.VirtualHost = virtualHost; IConnection conn = factory.CreateConnection(protocol, hostName, portNumber);
The IConnection interface can then be used to open a channel:
IModel channel = conn.CreateModel();
The channel can now be used to send and receive messages, as described in subsequent sections.
2.4. Disconnecting from a broker
To disconnect, simply close the channel and the connection:
channel.Close(200, "Goodbye"); conn.Close();
Note that closing the channel is considered good practice, but isn’t strictly necessary - it will be done automatically anyway when the underlying connection is closed.
In some situations, you may want the connection to close automatically once the last open channel on the connection closes. To achieve this, set thetuA.noitcennoCIoCloseproperty to true, but onlyafter creating the first channel:
IConnection conn = factory.CreateConnection(...); IModel channel = conn.CreateModel(); conn.AutoClose = true;
WhenCotuesolAlast channel to close will also cause the connection to closeis true, the 1. If it is set to true before any channel is created, the connection will close then and there.
2.5. Using exchanges and queues
Client applications work with exchanges and queues, the high-level building blocks of AMQP. These must be "declared" before they can be used. Declaring either type of object simply ensures that one of that name exists, creating it if necessary.
Continuing the previous example, the following code declares an exchange and a queue, then binds them together.
channel.ExchangeDeclare(exchangeName, ExchangeType.Direct); channel.QueueDeclare(queueName); channel.QueueBind(queueName, exchangeName, routingKey, false, null);
7
This will actively declare the following objects:
1. a non-durable, non-autodelete exchange of "direct" type
2. a non-durable, non-exclusive, non-autodelete queue
RabbitMQ .NET Client Library User Guide
both of which can be customised by using additional parameters. Here neither of them have any special arguments.
The above code then binds the queue to the exchange with the given routing key.
Note that these Channel API methods are overloaded. These convenient short forms of ExchangeDeclare and QueueDeclare use sensible defaults. There are also longer forms with more parameters, to let you override these defaults as necessary, giving full control where needed.
This "short version, long version" pattern is used throughout the API.
2.6. Publishing messages
To publish a message to an exchange, useIdeMoilbuhsaB.lPcisas follows: byte[] messageBodyBytes = System.Text.Encoding.UTF8.GetBytes("Hello, world!"); channel.BasicPublish(exchangeName, routingKey, null, messageBodyBytes);
For fine control, you can use overloaded variants to specify the mandatory and immediate flags, or send messages with basic-class header properties:
byte[] messageBodyBytes = System.Text.Encoding.UTF8.GetBytes("Hello, world!"); IBasicProperties props = channel.CreateBasicProperties(); props.ContentType = "text/plain"; props.DeliveryMode = 2; channel.BasicPublish(exchangeName, routingKey, props, messageBodyBytes);
This sends a message with delivery mode 2 (persistent) and content-type "text/plain". See the definition of theesertiPropsaciBIinterface for more information about the available header properties.
2.7. Retrieving individual messages
To retrieve individual messages, useI.laBoMedcGsiet. The returned value is an instance of BasicGetResult, from which the header information (properties) and message body can be extracted:
bool noAck = false;
8
RabbitMQ .NET Client Library User Guide
BasicGetResult result = channel.BasicGet(queueName, noAck); if (result == null) { // No message available at this time. } else { IBasicProperties props = result.BasicProperties; byte[] body = result.Body; ...
SincenoAck = falseabove, you must also callB.sadolekcicAIMto acknowledge that you have successfully received and processed the message:
}
... // acknowledge receipt of the message channel.BasicAck(result.DeliveryTag, false);
2.8. Retrieving messages by subscription
Another way to receive messages is to set up a subscription using thereoCcimusnasIBinterface. The messages will then be delivered automatically as they arrive, rather than having to be requested proactively.
The easiest and safest way to implement a consumer is to use the convenience class QueueingBasicConsumer, and retrieve deliveries from theSerahdQueueinstance contained therein: QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel); channel.BasicConsume(queueName, null, consumer); while (true) { try { RabbitMQ.Client.Events.BasicDeliverEventArgs e = (RabbitMQ.Client.Events.BasicDeliverEventArgs) consumer.Queue.Dequeue(); IBasicProperties props = e.BasicProperties; byte[] body = e.Body; // ... process the message channel.BasicAck(e.DeliveryTag, false); } catch (OperationInterruptedException ex) { // The consumer was removed, either through // channel or connection closure, or through the // action of IModel.BasicCancel(). break; }
}
Another alternative is to subclassrmesuonCcisaBtluafeD, overriding methods as necessary, or implementmusnresaBIoCcidirectly. You will generally want to implement the core method HandleBasicDeliver.
9
RabbitMQ .NET Client Library User Guide
More sophisticated consumers will need to implement further methods. In particular, HandleModelShutdowntraps channel/connection closure. Consumers can also implement HandleBasicCancelOkto be notified of cancellations.
TheConsumerTagproperty ofeDafluBtsaCoicumnsercan be used to retrieve the server-generated consumer tag, in cases where none was supplied to the originalB.lecisadoMInsCoeumcall.
You can cancel an active consumer withlecnaCcisaB.leIMod:
channel.BasicCancel(consumerTag);
When calling the API methods, you always refer to consumers by their consumer tags, which can be either client- or server-generated as explained in the AMQP specification document.
2.9. Threading, deadlocks, and associated restrictions on consumers
EachnoionICctnecurrent implementation, backed by a single background threadinstance is, in the that reads from the socket and dispatches the resulting events to the application. Additionally there are two threads responsible foraetartbHesupport, if connection negotiation turned it on.
Usually, therefore, there will be four threads active in an application using this library: application logic, and makes calls onthe application thread: contains the IModelmethods to perform AMQP operations. the connection thread: hidden away and completely managed by theitnoIConnecinstance. the heartbeat read thread: continuously checking ifnoceitConnIinstance has not missed too many Heartbeatframes from the broker the heartbeat write thread: continuosuly checking ifonICoinentcinstance should sendarttbeHea frame to the broker
The one place where the nature of the threading model is visible to the application is in any callback the application registers with the library. Such callbacks include: anyrmeCcisusnoaBImethod theasButnrcieRevent onIModel any of the various shutdown events onontiecnnCoI,IModeletc.
Application callback handlersmust notinvoke blocking AMQP operations (such as IModel.QueueDeclareordel.BasiIMoCcnaecl). If they do, the channel will deadlock2.
10
RabbitMQ .NET Client Library User Guide
Only asynchronous AMQP operations are safe for use within callbacks, such as: asicAckIModel.B hissaciuPlbMIdoleB.
For this reason,ernsumoCcisaBgnieueuQis the safest way of subscribing to a queue, because its implementation usesaRbbtiQMU.til.SharedQueueto pass deliveries over to the application thread, where all processing of received deliveries is done, and where any AMQPIModeloperation is safe.
2.10. IModel should not be shared between threads
In general,IModelinstances should not be used by more than one thread simultaneously: application code should maintain a clear notion of thread ownership forIModeltansi.esnc
If more than one thread needs to access a particularIModelinstances, the application should enforce mutual exclusion itself. One way of achieving this is for all users of anIModeltolockthe instance itself:
IModel ch = RetrieveSomeSharedIModelInstance(); lock (ch) { ch.BasicPublish(...); }
Symptoms of incorrect serialisation ofIModeloperations include, but are not limited to,
invalid frame sequences being sent on the wire (which occurs, for example, if more than one BasicPublishoperation is run simultaneously), and/or NotSupportedExceptions being thrown from a method in classoioncaCtuneuntQiueRp complaining about"Pipelining of requests forbidden"(which occurs in situations where more than one AMQP RPC, such asgnDecxahercealE, is run simultaneously).
2.11. Handling unroutable or undelivered messages
If a message is published with the "mandatory" or "immediate" flags set, but cannot be delivered, the broker will return it to the sending client (via aeturic.rnsabAMQP command).
To be notified of such returns, clients can subscribe to theoMed.laBInsicReturevent. If there are no listeners attached to the event, then returned messages will be silently dropped.
channel.BasicReturn += new RabbitMQ.Client.Events.BasicReturnEventHandler(...);
11
  • Univers Univers
  • Ebooks Ebooks
  • Livres audio Livres audio
  • Presse Presse
  • Podcasts Podcasts
  • BD BD
  • Documents Documents