Chapter 5. Using the API
This chapter explains how to use the AMQ C++ API to perform common messaging tasks.
5.1. Basic operation Copy linkLink copied to clipboard!
5.1.1. Handling messaging events Copy linkLink copied to clipboard!
AMQ C++ is an asynchronous event-driven API. To define how the application handles events, the user implements callback methods on the messaging_handler class. These methods are then called as network activity or timers trigger new events.
Example: Handling messaging events
These are only a few common-case events. The full set is documented in the API reference.
5.1.2. Creating a container Copy linkLink copied to clipboard!
The container is the top-level API object. It is the entry point for creating connections, and it is responsible for running the main event loop. It is often constructed with a global event handler.
Example: Creating a container
int main() {
example_handler handler {};
proton::container cont {handler};
cont.run();
}
int main() {
example_handler handler {};
proton::container cont {handler};
cont.run();
}
Setting the container identity
Each container instance has a unique identity called the container ID. When AMQ C++ makes a connection, it sends the container ID to the remote peer. To set the container ID, pass it to the proton::container constructor.
Example: Setting the container identity
proton::container cont {handler, "job-processor-3"};
proton::container cont {handler, "job-processor-3"};
If the user does not set the ID, the library will generate a UUID when the container is constucted.
5.2. Network connections Copy linkLink copied to clipboard!
5.2.1. Connection URLs Copy linkLink copied to clipboard!
Connection URLs encode the information used to establish new connections.
Connection URL syntax
scheme://host[:port]
scheme://host[:port]
-
Scheme - The connection transport, either
amqpfor unencrypted TCP oramqpsfor TCP with SSL/TLS encryption. - Host - The remote network host. The value can be a hostname or a numeric IP address. IPv6 addresses must be enclosed in square brackets.
-
Port - The remote network port. This value is optional. The default value is 5672 for the
amqpscheme and 5671 for theamqpsscheme.
Connection URL examples
amqps://example.com amqps://example.net:56720 amqp://127.0.0.1 amqp://[::1]:2000
amqps://example.com
amqps://example.net:56720
amqp://127.0.0.1
amqp://[::1]:2000
5.2.2. Creating outgoing connections Copy linkLink copied to clipboard!
To connect to a remote server, call the container::connect() method with a connection URL. This is typically done inside the messaging_handler::on_container_start() method.
Example: Creating outgoing connections
See the Section 5.5, “Security” section for information about creating secure connections.
5.2.3. Configuring reconnect Copy linkLink copied to clipboard!
Reconnect allows a client to recover from lost connections. It is used to ensure that the components in a distributed system reestablish communication after temporary network or component failures.
AMQ C++ disables reconnect by default. To enable it, set the reconnect connection option to an instance of the reconnect_options class.
Example: Enabling reconnect
With reconnect enabled, if a connection is lost or a connection attempt fails, the client will try again after a brief delay. The delay increases exponentially for each new attempt.
To control the delays between connection attempts, set the delay, delay_multiplier, and max_delay options. All durations are specified in milliseconds.
To limit the number of reconnect attempts, set the max_attempts option. Setting it to 0 removes any limit.
Example: Configuring reconnect
5.2.4. Configuring failover Copy linkLink copied to clipboard!
AMQ C++ allows you to configure multiple connection endpoints. If connecting to one fails, the client attempts to connect to the next in the list. If the list is exhausted, the process starts over.
To specify alternate connection endpoints, set the failover_urls reconnect option to a list of connection URLs.
Example: Configuring failover
5.3. Message delivery Copy linkLink copied to clipboard!
5.3.1. Sending messages Copy linkLink copied to clipboard!
To send a message, override the on_sendable event handler and call the sender::send() method. The sendable event fires when the proton::sender has enough credit to send at least one message.
Example: Sending messages
5.3.2. Tracking sent messages Copy linkLink copied to clipboard!
When a message is sent, the sender can keep a reference to the tracker object representing the transfer. After the message is delivered, the receiver accepts or rejects it. The sender is notified of the outcome for each tracked delivery.
To monitor the outcome of a sent message, override the on_tracker_accept and on_tracker_reject event handlers and map the delivery state update to the tracker returned from send().
Example: Tracking sent messages
5.3.3. Receiving messages Copy linkLink copied to clipboard!
To receive messages, create a receiver and override the on_message event handler.
Example: Receiving messages
5.3.4. Acknowledging received messages Copy linkLink copied to clipboard!
To explicitly accept or reject a delivery, use the delivery::accept() or delivery::reject() methods in the on_message event handler.
Example: Acknowledging received messages
By default, if you do not explicity acknowledge a delivery, then the library accepts it after on_message returns. To disable this behavior, set the auto_accept receiver option to false.
5.4. Error handling Copy linkLink copied to clipboard!
Errors in AMQ C++ can be handled in two different ways:
- Catching exceptions
- Overriding virtual functions to handle AMQP protocol or connection errors
Catching exceptions
Catching exceptions is the most basic, but least granular, way to handle errors. If an error is not handled using an override in a handler routine, an exception will be thrown and can be caught and handled. An exception thrown in this way will be thrown by the container’s run method.
All of the exceptions that can be thrown by AMQ C++ are descended from proton::error, which in turn is a subclass of std::runtime_error (which is a subclass of std::exception).
The code example below illustrates how a block could be written to catch any exception thrown from AMQ C++.
Example: API-Specific exception handling
If you require no API-specific exception handling, you only need to catch std::exception since proton::error descends from it.
Example: General exception handling
Because all exceptions in a C++ program descend from std::exception, you can write a code block to wrap your main method and display information about any std::exception errors.
Handling connection and protocol errors
You can handle protocol-level errors by overriding the following messaging_handler methods:
-
on_transport_error(proton::transport&) -
on_connection_error(proton::connection&) -
on_session_error(proton::session&) -
on_receiver_error(proton::receiver&) -
on_sender_error(proton::sender&)
These event handling routines are called whenever there is an error condition with the specific object that is in the event. After calling the error handler, the appropriate close handler will also be called.
If not overridden the default error handler will be called with an indication of the error condition that occurred.
There is also a default error handler:
-
on_error(proton::error_condition&)
If one of the more specific error handlers is not overridden, this will be called.
As the close handlers will be called in the event of any error, only error itself need be handled within the error handler. Resource clean up can be managed by close handlers. If there is no error handling that is specific to a particular object it is typical to use the general on_error handler and not have a more specific handler.
5.5. Security Copy linkLink copied to clipboard!
5.5.1. Securing connections with SSL/TLS Copy linkLink copied to clipboard!
AMQ C++ uses SSL/TLS to encrypt communication between clients and servers.
To connect to a remote server with SSL/TLS, set the ssl_client_options connection option and use a connection URL with the amqps scheme. The ssl_client_options constructor takes the filename, directory, or database ID of a CA certificate.
Example: Enabling SSL/TLS
5.5.2. Connecting with a user and password Copy linkLink copied to clipboard!
AMQ C++ can authenticate connections with a user and password.
To specify the credentials used for authentication, set the user and password options on the connect method.
Example: Connecting with a user and password
5.5.3. Configuring SASL authentication Copy linkLink copied to clipboard!
AMQ C++ uses the SASL protocol to perform authentication. SASL can use a number of different authentication mechanisms. When two network peers connect, they exchange their allowed mechanisms, and the strongest mechanism allowed by both is selected.
The client uses Cyrus SASL to perform authentication. Cyrus SASL uses plug-ins to support specific SASL mechanisms. Before you can use a particular SASL mechanism, the relevant plug-in must be installed. For example, you need the cyrus-sasl-plain plug-in in order to use SASL PLAIN authentication.
To see a list of Cyrus SASL plug-ins in Red Hat Enterprise Linux, use the yum search cyrus-sasl command. To install a Cyrus SASL plug-in, use the yum install PLUG-IN command.
By default, AMQ C++ allows all of the mechanisms supported by the local SASL library configuration. To restrict the allowed mechanisms and thereby control what mechanisms can be negotiated, use the sasl_allowed_mechs connection option. It takes a string containing a space-separated list of mechanism names.
Example: Configuring SASL authentication
proton::connection_options opts {};
opts.sasl_allowed_mechs("ANONYMOUS");
container.connect("amqps://example.com", opts);
proton::connection_options opts {};
opts.sasl_allowed_mechs("ANONYMOUS");
container.connect("amqps://example.com", opts);
This example forces the connection to authenticate using the ANONYMOUS mechanism even if the server we connect to offers other options. Valid mechanisms include ANONYMOUS, PLAIN, SCRAM-SHA-256, SCRAM-SHA-1, GSSAPI, and EXTERNAL.
AMQ C++ enables SASL by default. To disable it, set the sasl_enabled connection option to false.
Example: Disabling SASL
proton::connection_options opts {};
opts.sasl_enabled(false);
container.connect("amqps://example.com", opts);
proton::connection_options opts {};
opts.sasl_enabled(false);
container.connect("amqps://example.com", opts);
5.5.4. Authenticating using Kerberos Copy linkLink copied to clipboard!
Kerberos is a network protocol for centrally managed authentication based on the exchange of encrypted tickets. See Using Kerberos for more information.
- Configure Kerberos in your operating system. See Configuring Kerberos to set up Kerberos on Red Hat Enterprise Linux.
Enable the
GSSAPISASL mechanism in your client application.proton::connection_options opts {}; opts.sasl_allowed_mechs("GSSAPI"); container.connect("amqps://example.com", opts);proton::connection_options opts {}; opts.sasl_allowed_mechs("GSSAPI"); container.connect("amqps://example.com", opts);Copy to Clipboard Copied! Toggle word wrap Toggle overflow Use the
kinitcommand to authenticate your user credentials and store the resulting Kerberos ticket.kinit USER@REALM
$ kinit USER@REALMCopy to Clipboard Copied! Toggle word wrap Toggle overflow - Run the client program.
5.6. Timers Copy linkLink copied to clipboard!
AMQ C++ has the ability to execute code after a delay. You can use this to implement time-based behaviors in your application, such as periodically scheduled work or timeouts.
5.6.1. Scheduling deferred work Copy linkLink copied to clipboard!
To defer work for a fixed amount of time, use the schedule method to set the delay and register a function defining the work.
Example: Sending a message after a delay
This example uses the schedule method on the work queue of the sender in order to establish it as the execution context for the work.
5.7. More information Copy linkLink copied to clipboard!
For more information, see the API reference.