I want my Python script to receive one message from a PubSub topic and then go on to other work. The code is learned from an example of the GCP document:
with subscriber: # The subscriber pulls a specific number of messages. The actual # number of messages pulled may be smaller than max_messages. response = subscriber.pull( request={"subscription": subscription_path, "max_messages": NUM_MESSAGES}, retry=retry.Retry(deadline=300), ) if len(response.received_messages) == 0: return
The problem is that it will receive empty messages, meaning that “len(response.received_messages)” is zero.
Where do these empty messages come from? Here is the answer:
Once a message is sent to a subscriber, the subscriber must either acknowledge or drop the message. A message is considered outstanding once it has been sent out for delivery and before a subscriber acknowledges it.
My solution is just to wait until receiving a non-empty message:
with subscriber: # The subscriber pulls a specific number of messages. The actual # number of messages pulled may be smaller than max_messages. while True: response = subscriber.pull( request={"subscription": subscription_path, "max_messages": NUM_MESSAGES}, retry=retry.Retry(deadline=300), ) if len(response.received_messages) > 0: break