IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Empty messages received by PubSub pull()

    RobinDong发表于 2023-05-11 23:55:07
    love 0

    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


沪ICP备19023445号-2号
友情链接