@@ -293,13 +293,38 @@ Result ConsumerImpl::handleCreateConsumer(const ClientConnectionPtr& cnx, Result
293293 Result handleResult = ResultOk;
294294
295295 if (result == ResultOk) {
296- LOG_INFO (getName () << " Created consumer on broker " << cnx->cnxString ());
297296 {
298297 Lock mutexLock (mutex_);
298+ if (!changeToReadyState ()) {
299+ auto client = client_.lock ();
300+ if (client) {
301+ LOG_INFO (getName () << " Closing subscribed consumer since it was already closed" );
302+ int requestId = client->newRequestId ();
303+ auto name = getName ();
304+ cnx->sendRequestWithId (Commands::newCloseConsumer (consumerId_, requestId), requestId)
305+ .addListener ([name](Result result, const ResponseData&) {
306+ if (result == ResultOk) {
307+ LOG_INFO (name << " Closed consumer successfully after subscribe completed" );
308+ } else {
309+ LOG_WARN (name << " Failed to close consumer: " << strResult (result));
310+ }
311+ });
312+ } else {
313+ // This should not happen normally because if client is destroyed, the connection pool
314+ // should also be closed, which means all connections should be closed. Close the
315+ // connection to let broker know this registered consumer is inactive.
316+ LOG_WARN (getName ()
317+ << " Client already closed when subscribe completed, close the connection "
318+ << cnx->cnxString ());
319+ cnx->close (ResultNotConnected);
320+ }
321+ return ResultAlreadyClosed;
322+ }
323+
324+ LOG_INFO (getName () << " Created consumer on broker " << cnx->cnxString ());
299325 setCnx (cnx);
300326 incomingMessages_.clear ();
301327 possibleSendToDeadLetterTopicMessages_.clear ();
302- state_ = Ready;
303328 backoff_.reset ();
304329 if (!messageListener_ && config_.getReceiverQueueSize () == 0 ) {
305330 // Complicated logic since we don't have a isLocked() function for mutex
0 commit comments