Sun Java System Message Queue 3.5 SP1 C Client Developer's Guide |
Chapter 3
Using the C APIThis chapter describes how to use C functions to accomplish specific tasks and provides brief code samples to illustrate some of these tasks. (For clarity, the code examples shown in the following sections omit a function call status check.)
Following a brief discussion of overall design and a summary of client tasks, the topics covered include the following:
This chapter does not provide exhaustive information about each function. For detailed function information, please see the description of that function in Chapter 4, "Reference".
For information on building Message Queue C programs, see Chapter 2, "Building and Running Message Queue C Clients".
Message Queue C Client Setup OperationsThe general procedures for producing and consuming messages are introduced below. The procedures have a number of common steps which need not be duplicated if a client is both producing and consuming messages.
To Set Up a Message Queue C Client to Produce Messages
- Call the MQCreateProperties function to get a handle to a properties object.
- Use one or more of the MQSet... Property functions to set connection properties that specify the name of the broker, its port number, and its behavior.
- Use the MQCreateConnection function to create a connection.
- Use the MQCreateSession function to create a session and to specify its acknowledge mode and its receive mode. If the session will be used only for producing messages, use the receive mode MQ_SESSION_SYNC_RECEIVE to avoid creating a thread for asynchronous message delivery.
- Use the MQCreateDestination function to specify a physical destination on the broker. The destination name you specify must be the same as the name of the physical destination.
- Use the MQCreateMessageProducer function or the MQCreateMessageProducerForDestination function to create a message producer. (If you plan to send a lot of messages to the same destination, you should use the MQCreateMessageProducerForDestination function.)
- Use the MQCreateBytesMessage function or the MQCreateTextMessage function to get a newly created message handle.
- Call the MQCreateProperties function to get a handle to a properties object that will describe the message header properties. This is only required if you want to set a message header property.
- Use one or more of the MQSet... Property functions to set properties that specify the value of the message header properties you want to set.
- Use the MQSetMessageHeaders function, passing a handle to the properties object you created in Step 8 and Step 9.
- Repeat Step 8 if you want to define custom message properties, and then use the MQSetMessageProperties function to set these properties for your message.
- Use the MQSetMessageReplyTo function if you want to specify a destination where replies to the message are to be sent.
- Use one of the MQSendMessage... functions to send the message.
To Set Up a Message Queue C Client to Consume Messages Synchronously
- Call the MQCreateProperties function to get a handle to a properties object.
- Use one or more of the MQSet... Property functions to set connection properties that specify the name of the broker, its port number, and its behavior.
- Use the MQCreateConnection function to create a connection.
- Use the MQCreateSession function to create a session and to specify its receive mode. Specify MQ_SESSION_SYNC_RECEIVE for a synchronous session.
- Use the MQCreateDestination function to specify a destination on the broker from which the consumer is to receive messages. The destination name you specify must be the same as the name of the physical destination.
- Use the MQCreateMessageConsumer function or the MQCreateDurableMessageConsumer function to create a consumer.
- Use the MQStartConnection function to start the connection.
- Use one of the MQReceiveMessage... functions to start message delivery.
To Set Up a Message Queue C Client to Consume Messages Asynchronously
- Call the MQCreateProperties function to get a handle to a properties object.
- Use one or more of the MQSet... Property functions to set connection properties that specify the name of the broker, its port number, and its behavior.
- Use the MQCreateConnection function to create a connection.
- Use the MQCreateSession function to create a session and to specify its acknowledge mode and its receive mode. Specify MQ_SESSION_ASYNC_RECEIVE for asynchronous message delivery.
- Use the MQCreateDestination function to specify a destination on the broker from which the consumer is to receive messages. The logical destination name you specify must be the same as the name of the physical destination.
- Write a callback function of type MQMessageListenerFunc that will be called when the broker starts message delivery. In the body of this callback function, use the functions listed in Table 3-9, to process the contents of the incoming message.
- Use the MQCreateAsyncMessageConsumer function or the MQCreateAsyncDurableMessageConsumer function to create a consumer.
- Use the MQStartConnection function to start the connection and message delivery.
Working With PropertiesWhen you create a connection, set message header properties, or set user-defined message properties, you must pass a handle to a properties object. You use the MQCreateProperties function to create this object and to obtain a handle to it. When you receive a message, you can use specific MQGet...Property functions to obtain the type and value of each message property.
This section describes the functions you use to set and get properties. A property is defined as a key-value pair.
Setting Connection and Message Properties
You use the functions listed in Table 3-1 to create a handle to a properties object, and to set properties. You can use these functions to create and define properties for connections or for individual messages.
To Set Properties for a Connection
- Call the MQCreateProperties function to get a handle to a newly created properties object.
- Call one of the MQSet...Property functions to set one of the connection properties listed in Table 4-2. At a minimum, you must specify the name of the host of the broker to which you want to connect and its port number.
Which function you call depends on the type of the property you want to set; for example, to set an MQString property, you call the MQSetStringProperty function; to set an MQBool property, you call the MQSetBoolProperty function; and so on. Each function that sets a property requires that you pass a key name and value; these are listed and described in Table 4-2.
- When you have set all the properties you want to define for the connection, you can then create the connection, by calling the MQCreateConnection function.
Once the connection is created with the properties you specify, you cannot change its properties. If you need to change connection properties after you have created a connection, you will need to destroy the old connection and its associated objects and create a new one with the desired properties. It is a good idea to think through the desired behavior before you create a connection.
Code Example 3-1 illustrates how you create a properties handle and how you use it for setting connection properties.
The Message Queue C client runtime sets the connection properties that specify the name and version of the Message Queue product; you can retrieve these using the MQGetMetaData function. These properties are described at the end of Table 4-2, starting with MQ_NAME_PROPERTY.
To Set Message Properties
Set message properties and message header properties using the same procedure you used to set connection properties. You can set the following message header properties for sending a message:
For more information, see MQSetMessageProperties.
Getting Message Properties
When you receive a message, if you are interested in the message properties, you need to obtain a handle to the properties object associated with that message:
- Use the MQGetMessageProperties function to obtain a handle to the properties object for user-defined properties.
- If you are interested in any message header properties, use the MQGetMessageHeaderProperties function to obtain a handle to the header properties. See Table 4-5.
Having obtained the handle, you can then iterate through the properties and then use the appropriate MQGet...Property function to determine the type and value of each property.
Table 3-2 lists the functions you use to iterate through a properties handle and to obtain the type and value of each property.
Table 3-2 Functions Used to Get Message Properties
Function
Description
Starts the iteration process through the specified properties handle
Returns MQ_TRUE if there are additional property keys left in the iteration.
Passes back the address of the next property key in the referenced property handle.
Gets the type of the specified property.
Gets the value of the specified MQBool type property.
Gets the value of the specified MQString type property.
Gets the value of the specified MQInt8 type property.
Gets the value of the specified MQInt16 type property.
Gets the value of the specified MQInt32 type property.
Gets the value of the specified MQInt64 type property.
Gets the value of the specified MQFloat32 type property.
Gets the value of the specified MQFloat64 type property.
To Iterate Through a Properties Handle
- Start the process by calling the MQPropertiesKeyIterationStart function.
- Loop using the MQPropertiesKeyIterationHasNext function.
- Extract the name of each property key by calling the MQPropertiesKeyIterationGetNext function.
- Determine the type of the property value for a given key by calling the MQGetPropertyType function.
- Use the appropriate MQGet...Property function to find the value of the specified property key and type.
If you know the property key, you can just use the appropriate MQGet...Property function to get its value. Code Example 3-2 illustrates how you implement these steps.
Code Example 3-2 Getting Property Values for a Message Header
MQStatus status;
MQPropertiesHandle headersHandle = MQ_INVALID_HANDLE;
MQBool redelivered;
ConstMQString my_msgtype;
status = (MQGetMessageHeaders(messageHandle, &headersHandle));
status = (MQGetBoolProperty(headersHandle,
MQ_REDELIVERED_HEADER_PROPERTY, &redelivered));
status = MQGetStringProperty(headersHandle,
MQ_MESSAGE_TYPE_HEADER_TYPE_PROPERTY, &my_msgtype);
Working With ConnectionsAll messaging occurs within the context of a connection: the behavior of the connection is defined by the properties set for that connection. These properties specify the following information:
You use the functions listed in Table 3-3 to create, start, stop, and close a connection.
Table 3-3 Functions Used to Work with Connections
Function
Description
Initializes the SSL library. You must call this function before you create any connection that uses SSL.
Creates a connection and passes back a handle to it.
Starts the specified connection and starts or resumes delivery of messages.
Stops the specified connection.
Returns a handle to name and version information for the Message Queue product.
Closes the specified connection.
Before you create a connection, you must do the following:
- Define the connection properties. See Setting Connection and Message Properties for more information.
- Specify a user name and password for the connection. See the Message Queue Administration Guide for information on how to set up users.
- Write a connection exception listener function. You will need to pass a reference to this listener when you create the connection. This function will be called synchronously when a connection exception occurs for this connection. For more information, see Callback Type for Connection Exception Handling.
- If you want a secure connection, call the MQIntitializeSSL function to initialize security. This initializes the SSL library. See Working With Secure Connections for more information.
When you have completed these steps, you are ready to call MQCreateConnection to create a connection. After you create the connection, you can create a session as described in Working With Sessions and Destinations.
When you send a message, you do not need to start the connection explicitly by calling MQStartConnection. You do need to call MQStartConnection before the broker can deliver messages to a consumer.
If you need to halt delivery in the course of processing messages, you can call the MQStopConnection function.
Working With Secure Connections
To set up a secure connection, you need to call the MQInitializeSSl function once (and only once) before you call the MQCreateConnection function, and you must set the MQ_CONNECTION_TYPE_PROPERTY to SSL. Depending on the operating system, you might also need to locate or create NSS certificate database files.
The MQInitializeSSl function initializes the NSS library. The certificateDatabasePath parameter you pass to the MQInitializeSSL function should point to a directory that contains the NSS files certN.db, keyN.db, and secmod.db (where N is a numeric digit). These certificate database files are opened read-only by the MQInitializeSSL function. You can generate the NSS certificate database files by using the Netscape or Mozilla browser. You can find the NSS certificate database files in the directory where the Netscape or Mozilla browser stores user settings, preferences, and bookmarks. For Mozilla, these files might not be created automatically. In that case, you can have them created by doing the following:
Solaris 8 or 9 comes with the Netscape browser, as does RedHat Linux. For Windows, you can download the Mozilla browser from the following location:
After you call the MQInitializeSSL function, you can call MQCreateConnection to create an SSL connection to the Message Queue broker by setting the connection property MQ_CONNECTION_TYPE_PROPERTY to SSL. Setting the connection property MQ_SSL_BROKER_IS_TRUSTED to MQ_TRUE (the default is MQ_FALSE) is not tested or supported in this release. Before running your Message Queue C client application over SSL, you should configure the Message Queue broker to enable SSL-based connection services. See the Message Queue Administration Guide for instructions on configuring the broker.
Shutting Down Connections
In order to do an orderly shutdown, you need to close the connection by calling MQCloseConnection and then to free the memory associated with the connection by calling the MQFreeConnection function.
- Closing the connection closes all sessions, producers, and consumers created from this connection. This also forces all threads associated with this connection that are blocking in the library to return.
- After all the application threads associated with this connection and its descendant sessions, producers, consumers, etc. have returned, the application can call the MQFreeConnection function to release all resources associated with the connection.
To get information about a connection, call the MQGetMetaData function. This returns name and version information for the Message Queue product.
Working With Sessions and DestinationsA session is a single-threaded context for producing and consuming messages. You can create multiple producers and consumers for a session, but you are restricted to using them serially. In effect, only a single logical thread of control can use them.
Table 3-4 describes the functions you use to create and manage sessions.
Table 3-4 Functions Used to Work with Sessions
Function
Description
Creates the specified session and passes back a handle to it.
Passes back the acknowledgement mode of the specified session.
Stops message delivery and restarts message delivery with the oldest unacknowledged message. (For non-transacted sessions.)
Rolls back a transaction associated with the specified session.
Commits a transaction associated with the specified session.
Closes the specified session.
Creating a Session
The MQCreateSession function creates a new session and initializes a handle to it in the sessionHandle parameter. The number of sessions you can create for a single connection is limited only by system resources. You can create a session after you have created a connection.
When you create a session, you specify whether it is transacted, the acknowledge mode, and the receive mode. After you create a session, you can create the producers, consumers, and destinations that use the session context to do their work.
Transacted Sessions
If you specify that a session be transacted, the acknowledge mode is ignored. Within a transacted session, the broker tracks sends and receives, completing these operations only when the client issues a call to commit the transaction. If a send or receive operation fails, an exception is raised. Your application can handle the exception by ignoring it, retrying it, or rolling back the entire transaction. When a transaction is committed, all the successful operations are completed. When a transaction is rolled back, all successful operations are cancelled.
Message Acknowledgement
When a message is delivered to a receiving client, the broker waits for the client to acknowledge receipt of a message before deleting the message from the broker’s destination.
The receiving client can control messaging reliability by setting the session’s acknowledge mode to one of the following values:
- MQ_AUTO_ACKNOWLEDGE specifies that the session automatically acknowledge each message consumed by the client.
- MQ_CLIENT_ACKNOWLEDGE specifies that the client must explicitly acknowledge messages by calling MQAcknowledgeMessages. In this case, all messages are acknowledged that have been consumed up to the point where the acknowledge function is called.
- MQ_DUPS_OK_ACKNOWLEDGE specifies that the session acknowledges receipt of messages after each ten messages are consumed.
The setting of the connection property MQ_ACK_ON_ACKNOWLEDGE_PROPERTY also determines the effect of some of these acknowledge modes. For more information, see Table 4-2.
Receive Mode
You can specify a session’s receive mode as either MQ_SESSION_SYNC_RECEIVE or MQ_SESSION_ASYNC_RECEIVE. If the session you create will be used for sending messages only, you should specify MQ_SESSION_SYNC_RECEIVE for its receive mode for optimization because the asynchronous receive mode automatically allocates an additional thread for the delivery of messages it expects to receive.
Managing a Session
Managing a session involves using threads appropriately for the type of session (synchronous or asynchronous) and managing message delivery for both transacted and nontransacted sessions. For more information, see Single-Threaded Session Control.
- For a session that is not transacted, use the MQRecoverSession function to restart message delivery with the last unacknowledged message.
- For a session that is transacted, use the MQRollBackSession function to roll back any messages that were delivered within this transaction. Use the MQCommitSession function to commit all messages associated with this transaction.
- Use the MQCloseSession function to close a session and all its associated producers and consumers. This function also frees memory allocated for the session.
You can get information about a session’s acknowledgment mode by calling the MQGetAcknowledgeMode function.
Creating Destinations
After creating a session, you can create destinations or temporary destinations for the messages you want to send. Table 3-5 lists the functions you use to create and to get information about destinations.
Table 3-5 Functions Used to Work with Destinations
Functions
Description
Creates a destination and initializes a handle to it.
Creates a temporary destination and initializes a handle to it.
Returns the type (queue or topic) of the specified destination.
The MQCreateDestination function creates a destination object and passes a handle to it back to you. In a production environment, the Message Queue administrator has to also create a physical destination on the broker, whose name and type is the same as that of the destination object, in order for messaging to happen. For example, if you use the MQCreateDestination function to create a queue destination called myMailQDest, the administrator has to create a physical destination on the broker named myMailQDest.
By default, the imq.autocreate.topic and imq.autocreate.queue properties for the broker are turned on. In this case, which is more convenient in a development environment, the broker automatically creates a physical destination whenever a message consumer or message producer attempts to access a non-existent destination. The auto-created physical destination will have the same name as that of the destination you created using the MQCreateDestination function.
You use the MQCreateTemporaryDestination to create a temporary destination. You can use such a destination to implement a simple request/reply mechanism. When you pass the handle of a temporary destination to the MQSetMessageReplyTo function, the consumer of the message can use that handle as the destination to which it sends a reply.
Temporary destinations are explicitly created by client applications and are automatically deleted when the connection is closed. They are maintained (and named) by the broker only for the duration of the connection for which they are created. Temporary destinations are system-generated uniquely for their connection and only their own connection is allowed to create message consumers for them.
Use the MQGetDestinationType function to determine the type of a destination: queue or topic. There may be times when you do not know the type of the destination to which you are replying: for example, when you get a handle from the MQGetMessageReplyTo function. Because the semantics of queue and topic destinations differ, you need to determine the type of a destination in order to reply appropriately.
Working With MessagesThis section describes how you use the C-API to complete the following tasks:
Composing Messages
You can create either a text message or a bytes message. A message, whether text or bytes, is composed of a header, properties, and a body. Table 3-6 lists the functions you use to construct messages.
Table 3-6 Functions Used to Construct Messages
Function
Description
Creates an MQ_BYTES_MESSAGE message.
Creates an MQ_TEXT_MESSAGE message.
Sets message header properties. (Optional)
Sets user-defined message properties.
Sets the body of an MQ_TEXT_MESSAGE message.
Sets the body of an MQ_BYTES_MESSAGE message.
Specifies the destination where replies to this message should be sent.
You begin by creating a message using either the MQCreateBytesMessage function or the MQCreateTextMessage function. Either of these functions return a message handle that you can then pass to the functions you use to set the message body, header, and properties using the functions listed in Table 3-6.
- Use the MQSetStringProperty function to define the body of a text message; use the MQSetBytesMessageBytes function to define the body of a bytes message.
- Use the MQSetMessageHeaders to set any message header properties.
- Use the MQSetMessageProperties function to set any user-defined properties for this message.
When you set message header properties or when you set additional user-defined properties, you must pass a handle to a properties object that you have created using the MQCreateProperties function. For more information, see Working With Properties.
You can use the MQSetMessageReplyTo function to associate a message with a destination that recipients can use for replies. To do this, you must first create a destination that will serve as your reply-to destination. Then, pass a handle to that destination when you call the MQSetMessageReplyTo function. The receiver of a message can use the MQGetMessageReplyTo function to determine whether a sender has set up a destination where replies are to be sent.
Sending a Message
Messages are sent by a message producer within the context of a connection and a session. Once you have obtained a connection, created a session, and composed your message, you can use the functions listed in Table 3-7 to create a message producer and to send the message.
Which function you choose to send a message depends on the following factors:
If you created a message producer with no specified destination, you must used one of the ...ToDestination send functions. If you created a message producer with a specified destination, you must use one of the other send functions
Table 3-7 Functions for Sending Messages
Function
Action
Creates a message producer with no specified destination.
Creates a message producer with a specified destination.
Sends a message for the specified producer.
Sends a message for the specified producer and allows you to set priority, time-to-live, and delivery mode.
Sends a message to the specified destination.
Sends a message to the specified destination and allows you to set priority, time-to-live, and delivery mode.
If you send a message using one of the functions that does not allow you to override header properties, the following message header fields are set to default values by the send function.
To override these values, use one of the extended send functions. For a complete list of message header properties, see Table 4-5.
Message headers also contain fields that can be set by the sending client; in addition, you can set user-defined message properties as well. For more information, see Composing Messages.
You can set the broker property MQ_ACK_ON_PRODUCE_PROPERTY to make sure that the message has reached its destination on the broker:
- By default, the broker acknowledges receiving persistent messages only.
- If you set the property to MQ_TRUE, the broker acknowledges receipt of all messages (persistent and non-persistent) from the producing client.
- If you set the property to MQ_FALSE, the broker does not acknowledge receipt of any message (persistent or non-persistent) from the producing client.
Note that “acknowledgement” in this case is not programmatic but internally implemented. That is, the client thread is blocked and does not return until the broker acknowledges messages it receives.
An administrator can set a broker limit, REJECT_NEWEST, which allows the broker to avert memory problems by rejecting the newest incoming message. If the incoming message is persistent, then an exception is thrown which the sending client should handle, perhaps by retrying the send a bit later. If the incoming message is not persistent, the client has no way of knowing that the broker rejected it. The broker might also reject a message if it exceeds a specified limit.
Receiving Messages
Messages are received by a message consumer in the context of a connection and a session. In order to receive messages, you must explicitly start the connection by calling the MQStartConnection function.
Table 3-8 lists the functions you use to create message consumers and to receive messages.
Table 3-8 Functions Used to Receive Messages
Function
Description
Creates the specified synchronous consumer and passes back a handle to it.
Creates a durable synchronous message consumer for the specified destination.
Creates an asynchronous message consumer for the specified destination.
Creates a durable asynchronous message consumer for the specified destination.
Unsubscribes the specified durable message consumer.
Passes a handle back to a message delivered to the specified consumer if a message is available; otherwise it returns an error.
Passes a handle back to a message delivered to the specified consumer if a message is available; otherwise it blocks until a message becomes available.
Passes a handle back to a message delivered to the specified consumer if a message is available within the specified amount of time.
Acknowledges the specified message and all messages received before it on the same session
Closes the specified consumer.
Working With Consumers
When you create a consumer, you need to make several decisions:
If you create a synchronous consumer, you can call one of three kinds of receive functions to receive your messages. If you create an asynchronous consumer, you must specify the name of a callback function that the client runtime can call when a message is delivered to the destination for that consumer. For information about the callback function signature, see Callback Type for Asynchronous Messaging.
A durable consumer receives all the messages published to a topic, including the ones published while the subscriber is inactive. A nondurable consumer only receives messages while the subscriber is active.
The broker retains a record of this durable subscription and makes sure that all messages from the publishers to this topic are retained until they are either acknowledged by this durable subscriber or until they have expired. Sessions with durable subscribers must always provide the same client identifier. In addition, each consumer must specify a durable name using the durableName parameter, which uniquely identifies (for each client identifier) each durable subscription it creates.
A session’s consumers are automatically closed when you close the session or connection to which they belong. However, messages will be routed to the durable subscriber while it is inactive and delivered when a new durable consumer is recreated. To close a consumer without closing the session or connection to which it belongs, use the MQCloseMessageConsumer function. If you want to close a durable consumer permanently, you should call the function MQUnsubscribeDurableMessageConsumer after closing it, to delete state information maintained by the broker on behalf of the durable consumer.
Receiving a Message Synchronously
If you have created a synchronous consumer, you can use one of three receive functions: MQReceiveMessageNoWait, MQReceiveMessageWait, or MQReceiveMessagewithTimeOut. In order to use any of these functions, you must have specified MQ_SESSION_SYNC_RECEIVE for the receive mode when you created the session.
When you create a session you must specify one of several acknowledge modes for that session. If you specify MQ_CLIENT_ACKNOWLEDGE as the acknowledge mode for the session, you must explicitly call the MQAcknowledgeMessages function to acknowledge messages that you have received. If the session is transacted, the acknowledge mode parameter is ignored.
When the receiving function returns, it gives you a handle to the delivered message. You can pass that handle to the functions described in Processing a Message, in order to read message properties and information stored in the header and body of the message.
Receiving a Message Asynchronously
To receive a message asynchronously, you must create an asynchronous message consumer and pass the name of an MQMessageListenerFunc type callback function. (Therefore, you must set up the callback function before you create the asynchronous consumer that will use it.) You should start the connection only after creating an asynchronous consumer. If the connection is already started, you should stop the connection before creating an asynchronous consumer.
You are also responsible for writing the message listener function. Mainly, the function needs to process the incoming message by examining its header, body, and properties, or it needs to pass control to a function that can do this processing. The client is also responsible for freeing the message handle (either from within the listener or from outside of the listener) by calling the MQFreeMessage function.
When you create a session you must specify one of several acknowledge modes for that session. If you specify MQ_CLIENT_ACKNOWLEDGE as the acknowledge mode for the session, you must explicitly call the MQAcknowledgeMessages function to acknowledge messages that you have received.
For more information about the signature and content of a call back function, see Callback Type for Asynchronous Messaging.
When the callback function is called by the session delivery of a message, it gives you a handle to the delivered message. You can pass that handle to the functions described in Processing a Message, in order to read message properties and information stored in the header and body of the message.
Processing a Message
When a message is delivered to you, you can examine the message’s properties, type, headers, and body. The functions used to process a message are described in Table 3-9.
Table 3-9 Functions Used to Process Messages
Function
Description
Gets message header properties.
Gets user-defined message properties.
Gets the message type: MQ_TEXT_MESSAGE or MQ_BYTES_MESSAGE
Gets the body of an MQ_TEXT_MESSAGE message.
Gets the body of an MQ_BYTES_MESSAGE message.
Gets the destination where replies to this message should be sent.
If you are interested in a message’s header information, you need to call the MQGetMessageHeaders function. If you need to read or check any user-defined properties, you need to call the MQGetMessageProperties function. Each of these functions passes back a properties handle. For information on how you can read property values, see Getting Message Properties.
Before you can examine the message body, you can call the MQGetMessageType function to determine whether the message is a text or bytes message. You can then call the MQGetTextMessageText, or the MQGetBytesMessageBytes function to get the contents of the message.
Some message senders specify a reply destination for their message. Use the MQGetMessageReplyTo function to determine that destination.
Error HandlingNearly all Message Queue C functions return an MQStatus result. You can use this return value to determine whether the function returned successfully and, if not, to determine the cause of the error.
Table 3-10 lists the functions you use to get error information.
Table 3-10 Functions Used in Handling Errors
Function
Description
Returns an MQ_TRUE if the specified MQStatus is an error.
Returns the error code for the specified MQStatus.
Returns a descriptive string for the specified MQStatus.
Returns the calling thread’s current error trace or NULL if no error trace is available.
To Handle Errors in Your Code
- Call MQStatusIsError, passing it an MQStatus result for the function whose result you want to test.
- If the MQStatusIsError function returns MQ_TRUE, call MQGetStatusCode or MQGetStatusString to identify the error.
- If the status code and string information is not sufficient to identify the cause of the error, you can get additional diagnostic information by calling MQGetErrorTrace to obtain the calling thread’s current error trace if this information is available.
Chapter 4, "Reference", lists common errors returned for each function. In addition to these errors, the following error codes may be returned by any Message Queue C function:
In addition, the MQ_TIMEOUT_EXPIRED can return from any Message Queue C function that communicates with the Message Queue broker if the connection MQ_ACK_TIMEOUT_PROPERTY is set to a non-zero value.
Memory ManagementTable 3-11 lists the functions you use to free or deallocate memory allocated by the Message Queue-C client library on behalf of the user. Such deallocation is part of normal memory management and will prevent memory leaks.
The functions MQCloseConnection, MQCloseSession, MQCloseMessageProducer, and MQCloseMessageConsumer are used to free resources associated with connections, sessions, producers, and consumers.
Table 3-11 Functions Used to Free Memory
Function
Description
Frees memory allocated to the specified connection.
Frees memory allocated to the specified destination.
Frees memory allocated to the specified message.
Frees memory allocated to the specified properties handle.
Frees memory allocated to the specified MQString.
You should free a connection only after you have closed the connection with the MQCloseConnection function and after all of the application threads associated with this connection and its dependent sessions, producers, and consumers have returned.
You should not free a connection while an application thread is active in a library function associated with this connection or one of its dependent sessions, producers, consumers, and destinations.
Freeing a connection does not release resources held by a message associated with this connection. You must free memory allocated for this message by explicitly calling the MQFreeMessage function.
You should not free a properties handle if the properties handle passed to a function becomes invalid on its return. If you do, you will get an error.
Thread ManagementThis section addresses a number of thread management issues that you should be aware of in designing and programming a Message Queue C client.
Message Queue C Runtime Thread Model
The Message Queue C-API library creates the thread(s) needed to provide runtime support for a Message Queue C client. It uses NSPR (Netscape Portable Runtime) GLOBAL threads. NSPR GLOBAL threads are fully compatible with native threads on each supported platform. Table 3-12 shows the thread model that the NSPR GLOBAL threads map to on each platform. For more information on NSPR, please see
http://www.mozilla.org/projects/nspr/
Table 3-12 Thread Model for NSPR GLOBAL Threads
Platform
Thread Model
Solaris
pthreads
Linux
pthreads
Windows
Win32 threads (from Microsoft Visual C++ runtime library msvcrt)
Concurrent Use of Handles
Table 3-13 lists the handles (objects) used in a C client program and specifies which of these may be used concurrently and which can only be used by one logical thread at a time.
Table 3-13 Handles and Concurrency
Handle
Supports Concurrent Use
MQDestinationHandle
YES
MQConnectionHandle
YES
MQSessionHandle
NO
MQProducerHandle
NO
MQConsumerHandle
NO
MQMessageHandle
NO
MQPropertiesHandle
NO
Single-Threaded Session Control
A session is a single-threaded context for producing and consuming messages. Multiple threads should not use the same session concurrently nor use the objects it creates concurrently. The only exception to this occurs during the orderly shutdown of the session or its connection when the client calls the MQCloseSession or the MQCloseConnection function.
- If a client wants to have one thread producing messages and other threads consuming messages, the client should use a separate session for its producing thread.
- Do not create an asynchronous message consumer while the connection is in started mode.
- A session created with MQ_SESION_ASYNC_RECEIVE mode uses a single thread to run all its consumers’ MQMessageListenerFunc callback functions. Clients that want concurrent delivery should use multiple sessions.
- Do not call the MQStopConnection, MQCloseSession, or the MQCloseConnection functions from a MQMessageListenerFunc callback function. (These calls will not return until delivery of messages has stopped.)
- You should call the MQFreeConnection function after MQCloseConnection and all of the application threads associated with a connection and its sessions, producers, consumers, etc., have returned.
The Message Queue C runtime library provides one thread to a session in MQ_SESSION_ASYNC_RECEIVE mode for asynchronous message delivery to its consumers. When the connection is started, all its sessions that have created asynchronous consumers are dedicated to the thread of control that delivers messages. Client code should not use such a session from another thread of control. The only exception to this is the use of MQCloseSession and MQCloseConnection.
Connection Exceptions
When a connection exception occurs, the Message Queue C library thread that is provided to the connection calls its MQConnectionExceptionListenerFunc callback if one exists. If an MQConnectionExceptionListenerFunc callback is used for multiple connections, it can potentially be called concurrently from different connection threads.
You should not call the MQCloseConnection function in an MQConnectionExceptionListenerFunc callback. Instead the callback function should notify another thread to call MQCloseConnection and return.
LoggingThe Message Queue C-API library uses two environment variables to control execution-time logging:
By default, .n (where n is 0, 1, 2,...) is appended to the actual log file name. This is used as a rotation index, and the indices are used sequentially when the maximum log file size is reached. You can use %g to specify a rotation index replacement in MQ_LOG_FILE after the last directory separator. Only the last %g is used if multiple %g’s are specified. the %g replacement can be escaped with %. The maximum rotation index is 9, and the maximum log file size is 1 MB. These limits are not configurable.