Chapter 5. Using the API


This chapter explains how to use the AMQ .NET API to perform common messaging tasks.

For more information, see the AMQ .NET API reference and AMQ .NET example suite.

5.1. Network connections

5.1.1. Creating outgoing connections

This section describes the standard format of the Connection URI string used to connect to an AMQP remote peer.

 scheme = ( "amqp" | "amqps" )
 host = ( <fully qualified domain name> | <hostname> | <numeric IP address> )

 URI = scheme "://" [user ":" [password] "@"] host [":" port]
  • scheme amqp - connection uses TCP transport and sets the default port to 5672.
  • scheme amqps - connection uses SSL/TLS transport and sets the default port to 5671.
  • user - optional connection authentication user name. If the user name is present then the client initiates an AMQP SASL user credential exchange during connection startup.
  • password - optional connection authentication password.
  • host - network host to which the connection is directed.
  • port - optional network port to which the connection is directed. The default port value is determined by the AMQP transport scheme.

Connection URI Examples

amqp://127.0.0.1
amqp://amqpserver.example.com:5672
amqps://joe:somepassword@bigbank.com
amqps://sue:secret@test.example.com:21000

5.2. Senders and receivers

The client uses sender and receiver links to represent channels for delivering messages. Senders and receivers are unidirectional, with a source end for the message origin, and a target end for the message destination.

Source and targets often point to queues or topics on a message broker. Sources are also used to represent subscriptions.

5.2.1. Creating queues and topics on demand

Some message servers support on-demand creation of queues and topics. When a sender or receiver is attached, the server uses the sender target address or the receiver source address to create a queue or topic with a name matching the address.

The message server typically defaults to creating either a queue (for one-to-one message delivery) or a topic (for one-to-many message delivery). The client can indicate which it prefers by setting the queue or topic capability on the source or target.

To select queue or topic semantics, follow these steps:

  1. Configure your message server for automatic creation of queues and topics. This is often the default configuration.
  2. Set either the queue or topic capability on your sender target or receiver source, as in the examples below.

Example: Sending to a queue created on demand

Target target = new Target() {
    Address = "jobs",
    Capabilities = new Symbol[] {"queue"},
};

SenderLink sender = new SenderLink(session, "s1", target, null);

Example: Receiving from a topic created on demand

Source source = new Source() {
    Address = "notifications",
    Capabilities = new Symbol[] {"topic"},
};

ReceiverLink receiver = new ReceiverLink(session, "r1", source, null);

For more information, see the following examples:

5.2.2. Creating durable subscriptions

A durable subscription is a piece of state on the remote server representing a message receiver. Ordinarily, message receivers are discarded when a client closes. However, because durable subscriptions are persistent, clients can detach from them and then re-attach later. Any messages received while detached are available when the client re-attaches.

Durable subscriptions are uniquely identified by combining the client container ID and receiver name to form a subscription ID. These must have stable values so that the subscription can be recovered.

To create a durable subscription, follow these steps:

  1. Set the connection container ID to a stable value, such as client-1:

    Connection conn = new Connection(new Address(connUrl),
                                     SaslProfile.Anonymous,
                                     new Open() { ContainerId = "client-1" },
                                     null);
  2. Configure the receiver source for durability by setting the Durable and ExpiryPolicy properties:

    Source source = new Source()
    {
        Address = "notifications",
        Durable = 2,
        ExpiryPolicy = new Symbol("never"),
    };
  3. Create a receiver with a stable name, such as sub-1, and apply the source properties:

    ReceiverLink receiver = new ReceiverLink(session, "sub-1", source, null);

To detach from a subscription, close the connection without explicitly closing the receiver. To terminate the subscription, close the receiver directly.

For more information, see the DurableSubscribe.cs example.

5.2.3. Creating shared subscriptions

A shared subscription is a piece of state on the remote server representing one or more message receivers. Because it is shared, multiple clients can consume from the same stream of messages.

The client configures a shared subscription by setting the shared capability on the receiver source.

Shared subscriptions are uniquely identified by combining the client container ID and receiver name to form a subscription ID. These must have stable values so that multiple client processes can locate the same subscription. If the global capability is set in addition to shared, the receiver name alone is used to identify the subscription.

To create a shared subscription, follow these steps:

  1. Set the connection container ID to a stable value, such as client-1:

    Connection conn = new Connection(new Address(connUrl),
                                     SaslProfile.Anonymous,
                                     new Open() { ContainerId = "client-1" },
                                     null);
  2. Configure the receiver source for sharing by setting the shared capability:

    Source source = new Source()
    {
        Address = "notifications",
        Capabilities = new Symbol[] {"shared"},
    };
  3. Create a receiver with a stable name, such as sub-1, and apply the source properties:

    ReceiverLink receiver = new ReceiverLink(session, "sub-1", source, null);

For more information, see the SharedSubscribe.cs example.

5.3. Message delivery

5.3.1. Sending messages

To send a message, create a connection, session, and sender link. Then call the Sender.Send() method with a Message object.

Example: Sending messages

Connection connection = new Connection(new Address("amqp://example.com"));
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-1", "jobs");

Message message = new Message("job-content");
sender.Send(message);

For more information, see the Send.cs example.

5.3.2. Receiving messages

To receive a message, create a connection, session, and receiver link. Then call the Receiver.Receive() method and use the returned Message object.

Example: Receiving messages

Connection connection = new Connection(new Address("amqp://example.com"));
Session session = new Session(connection);
ReceiverLink receiver = new ReceiverLink(session, "receiver-1", "jobs");

Message message = receiver.Receive();
receiver.Accept(message);

The Receiver.Accept() call tells the remote peer that the message was received and processed.

For more information, see the Receive.cs example.

5.4. Security

5.4.1. Connecting with a user and password

AMQ .NET can authenticate connections with a user and password.

To specify the credentials used for authentication, set the user and password fields in the connection URL.

Example: Connecting with a user and password

Address addr = new Address("amqp://<user>:<password>@example.com");
Connection conn = new Connection(addr);

5.4.2. Configuring SASL authentication

Client connections to remote peers may exchange SASL user name and password credentials. The presence of the user field in the connection URI controls this exchange. If user is specified then SASL credentials are exchanged; if user is absent then the SASL credentials are not exchanged.

By default the client supports EXTERNAL, PLAIN, and ANONYMOUS SASL mechanisms.

5.4.3. Configuring an SSL/TLS transport

Secure communication with servers is achieved using SSL/TLS. A client may be configured for SSL/TLS Handshake only or for SSL/TLS Handshake and client certificate authentication. See the Managing Certificates section for more information.

Note

TLS Server Name Indication (SNI) is handled automatically by the client library. However, SNI is signaled only for addresses that use the amqps transport scheme where the host is a fully qualified domain name or a host name. SNI is not signaled when the host is a numeric IP address.

5.5. Logging

Logging is important in troubleshooting and debugging. By default logging is turned off. To enable logging a user must set a logging level and provide a delegate function to receive the log messages.

5.5.1. Setting the log output level

The library emits log traces at different levels:

  • Error
  • Warning
  • Information
  • Verbose

The lowest log level, Error, will trace only error events and produce the fewest log messages. A higher log level includes all the log levels below it and generates a larger volume of log messages.

// Enable Error logs only.
Trace.TraceLevel = TraceLevel.Error
// Enable Verbose logs. This includes logs at all log levels.
Trace.TraceLevel = TraceLevel.Verbose

5.5.2. Enabling protocol logging

The Log level Frame is handled differently. Setting trace level Frame enables tracing outputs for AMQP protocol headers and frames.

Tracing at one of the other log levels must be ORed with Frame to get normal tracing output and AMQP frame tracing at the same time. For example

// Enable just AMQP frame tracing
Trace.TraceLevel = TraceLevel.Frame;
// Enable AMQP Frame logs, and Warning and Error logs
Trace.TraceLevel = TraceLevel.Frame | TraceLevel.Warning;

The following code writes AMQP frames to the console.

Example: Logging delegate

Trace.TraceLevel = TraceLevel.Frame;
Trace.TraceListener = (f, a) => Console.WriteLine(
        DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.