Ted Ross wrote:
I have a usage question about the C++ client api that is not addressed
by the examples.
My application needs to maintain a connection to the broker. If the
connection cannot be established, the application retries based on an
increasing interval. If the established connection is dropped, the
application attempts to reconnect.
This code fragment is the body (run method) of a connection thread (with
non-pertinent details removed for simplicity):
Connection connection;
Session session;
SubscriptionManager *subscriptions;
...
while (true) {
try {
connection.open(connectionSettings);
session = connection.newSession(queueName-string);
subscriptions = new client::SubscriptionManager(session);
subscriptions->subscribe(listener, queueName-string,
dest-string);
try {
subscriptions->run();
} catch (exception) {}
connection.close();
delete subscriptions;
subscriptions = 0;
} catch (exception &e) {
// adjust sleep delay
}
::sleep(delay);
}
Questions:
1) Is it ok to reuse the connection object (i.e. open => close => open)?
Should be; the state is all in ConnectionImpl of which a new instance is
created on open().
2) Is it ok to reuse the session object?
Yes.
Note that I never call
session.close or explicitly invoke its destructor.
You may want to session.sync() before closing if you are sending any
commands messages to the broker using an AsyncSession.
3) Is there anything wrong or inadvisable with the way I've done this?
You can catch TransportFailure as an indication of loss of connection
without any logical error occurring. An auto_ptr for the
SubscriptionManager pointer might be nicer, or even just allocate it on
the stack.