Pub\Sub Python 客户端 - 正常关闭订阅者

如何解决Pub\Sub Python 客户端 - 正常关闭订阅者

我在 python3.6 中使用 Google Pub/Sub 客户端 v2.2.0 作为订阅者。

我希望我的应用程序在确认它已经收到的所有消息后正常关闭。

Google 指南中订阅者的示例代码,稍作更改即可显示我的问题:

from concurrent.futures import TimeoutError
from google.cloud import pubsub_v1
from time import sleep

# TODO(developer)
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"
# Number of seconds the subscriber should listen for messages
# timeout = 5.0

subscriber = pubsub_v1.SubscriberClient()
# The `subscription_path` method creates a fully qualified identifier
# in the form `projects/{project_id}/subscriptions/{subscription_id}`
subscription_path = subscriber.subscription_path(project_id,subscription_id)

def callback(message):
    print(f"Received {message}.")
    sleep(30)
    message.ack()
    print("Acked")

streaming_pull_future = subscriber.subscribe(subscription_path,callback=callback)
print(f"Listening for messages on {subscription_path}..\n")

# Wrap subscriber in a 'with' block to automatically call close() when done.
with subscriber:
    sleep(10)
    streaming_pull_future.cancel()
    streaming_pull_future.result()

来自https://cloud.google.com/pubsub/docs/pull

我希望这段代码停止拉取消息并完成正在运行的消息然后退出。

实际上这段代码会停止拉取消息并完成正在运行的消息的执行,但它不会确认消息。 .ack() 发生了,但服务器没有收到 ack,所以接下来运行相同的消息再次返回。

1.为什么服务器没有收到 ack?

2.如何优雅地关闭订阅者?

3. .cancel() 的预期行为是什么?

解决方法

更新 (v2.4.0+)

客户端版本 2.4.0 向流式拉取未来的 await_msg_callbacks 方法添加了一个新的可选参数 cancel()。如果设置为 True,该方法将阻塞,直到所有当前正在执行的消息回调完成且后台消息流已关闭(默认为 False)。

try:
    streaming_pull_future.result()
except KeyboardInterrupt:
    streaming_pull_future.cancel(await_msg_callbacks=True)  # blocks until done

一些发行说明:

  • 等待回调意味着在其中生成的任何消息 ACK 仍将被处理(读取:发送到后端)。
  • 如果 await_msg_callbacksFalse 或未给出,则关闭将继续进行而无需等待。 cancel() 返回后,回调可能仍在后台运行,但它们生成的任何 ACK 都将无效,因为将不再有任何线程运行以将 ACK 请求分派到后端。
  • 位于客户端内部队列中的消息现在会在关闭时自动 NACK。无论 await_msg_callbacks 值如何,都会发生这种情况。

原始答案(v2.3.0 及以下)

流拉由流拉管理器在后台管理。当流式拉取 Future 为 canceled 时,它会调用管理器的 close() 方法,该方法优雅地关闭后台帮助线程。

被关闭的东西之一是调度程序 - 它是一个线程池,用于将接收到的消息异步分派给用户回调。需要注意的关键是 scheduler.shutdown() 不会等待用户回调完成,因为它可能会“永远”阻塞,而是清空执行器的工作队列并关闭后者:

def shutdown(self):
    """Shuts down the scheduler and immediately end all pending callbacks.
    """
    # Drop all pending item from the executor. Without this,the executor
    # will block until all pending items are complete,which is
    # undesirable.
    try:
        while True:
            self._executor._work_queue.get(block=False)
    except queue.Empty:
        pass
    self._executor.shutdown()

这解释了为什么在提供的代码示例中没有发送 ACK - 回调会休眠 30 秒,而流拉未来仅在大约 10 秒后被取消。 ACK 不会发送到服务器。

杂项。备注

  • 由于流式拉取是一个长时间运行的操作,我们希望在主线程中阻塞,以免过早退出。这是通过阻止流式拉取未来结果来完成的:
try:
    streaming_pull_future.result()
except KeyboardInterrupt:
    streaming_pull_future.cancel()

或在预设超时后:

try:
    streaming_pull_future.result(timeout=123)
except concurrent.futures.TimeoutError:
    streaming_pull_future.cancel()
  • ACK 请求是尽力而为的。即使关闭被阻止并等待用户回调完成,仍然无法保证消息确实会得到确认(例如,请求可能会在网络中丢失)。

  • Re:关于重新传递消息的担忧(“所以下次运行相同的消息会再次返回”) - 这实际上是设计使然。后端将努力传递每条消息 at least once,因为请求可能会丢失。这包括来自订阅者的 ACK 请求,因此在设计订阅者应用程序时必须考虑到幂等性。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res