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:
Python
x
10
10
1
with subscriber:
2
# The subscriber pulls a specific number of messages. The actual
3
# number of messages pulled may be smaller than max_messages.
4
response = subscriber.pull(
5
request={"subscription": subscription_path, "max_messages": NUM_MESSAGES},
6
retry=retry.Retry(deadline=300),
7
)
8
9
if len(response.received_messages) == 0:
10
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:
Python
1
11
11
1
with subscriber:
2
# The subscriber pulls a specific number of messages. The actual
3
# number of messages pulled may be smaller than max_messages.
4
while True:
5
response = subscriber.pull(
6
request={"subscription": subscription_path, "max_messages": NUM_MESSAGES},
7
retry=retry.Retry(deadline=300),
8
)
9
10
if len(response.received_messages) > 0:
11
break