将侦听器部署到 VPS 的最佳方式?

Best way to deploy a listener to a VPS?

我正在尝试将侦听器部署到 VPS,这将 运行 24/7。

侦听器的样板如下:

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

# 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: pubsub_v1.subscriber.message.Message) -> None:
    print(f"Received {message}.")
    message.ack()

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:
    try:
        # When `timeout` is not set, result() will block indefinitely,
        # unless an exception is encountered first.
        streaming_pull_future.result(timeout=timeout)
    except TimeoutError:
        streaming_pull_future.cancel()  # Trigger the shutdown.
        streaming_pull_future.result()  # Block until the shutdown is complete.

我的问题是,如果我将其部署到 VPS 和 运行 python3 listener.py,即使我关闭与 VPS?如果没有,我如何部署和 运行 这个程序,以便它继续 24/7 收听?

不,程序会在 SSH 连接完成后关闭。

有两种主要方法可以避免这种情况:Docker和手动部署。我将向您展示第二种方式的示例。您可以自己阅读 Docker。

在您的脚本旁边创建一个文件 listener.service

[Unit]
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/bin/python3 /usr/local/bin/listener-247
Restart=always

[Install]
WantedBy=multi-user.target

还有另一个 Bash 脚本 deploy.sh。您必须 运行 它才能更新服务器上的软件版本。将变量 SERVER_SSH 的值替换为您自己的值。此脚本假定您以 root 身份登录到服务器:

#!/usr/bin/bash
SERVER_SSH=root@example.org

scp ./listener.py $SERVER_SSH:/usr/local/bin/listener-247
ssh $SSH_SERVER chmod 755 /usr/local/bin/listener-247

scp ./listener.service $SERVER_SSH:/lib/systemd/system/listener-247.service
ssh $SSH_SERVER systemctl daemon-reload
ssh $SSH_SERVER systemctl enable listener-247
ssh $SSH_SERVER systemctl restart listener-247