arrow_back

Pub/Sub:Qwik Start - Python

登录 加入
Quick tip: Review the prerequisites before you run the lab
Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.
欢迎加入我们的社区,一起测试和分享您的知识!
done
学习 700 多个动手实验和课程并获得相关技能徽章

Pub/Sub:Qwik Start - Python

实验 30 分钟 universal_currency_alt 1 积分 show_chart 入门级
info 此实验可能会提供 AI 工具来支持您学习。
欢迎加入我们的社区,一起测试和分享您的知识!
done
学习 700 多个动手实验和课程并获得相关技能徽章

GSP094

Google Cloud 自學實驗室標誌

總覽

透過 Pub/Sub 服務,應用程式就能以可靠、快速、非同步的方式交換訊息。運作方式為資料產生者將訊息發布至 Cloud Pub/Sub 主題,然後訂閱者用戶端會建立對該主題的訂閱,並提取來自訂閱項目的訊息。Cloud Pub/Sub 能保留無法可靠傳送的訊息,最多七天。

在本研究室中,您將瞭解如何使用 Python 用戶端程式庫,透過 Pub/Sub 發布訊息。

學習內容

在本研究室中,您將學習以下內容:

  • 瞭解 Pub/Sub 的基本知識
  • 建立、刪除及列出 Pub/Sub 主題和訂閱項目
  • 將訊息發布至主題。
  • 使用提取訂閱者輸出個別主題訊息。

設定和需求

點選「Start Lab」按鈕前的須知事項

請詳閱以下操作說明。研究室活動會計時,而且中途無法暫停。點選「Start Lab」 後就會開始計時,讓您瞭解有多少時間可以使用 Google Cloud 資源。

您將在真正的雲端環境中完成實作研究室活動,而不是在模擬或示範環境。為達此目的,我們會提供新的暫時憑證,讓您用來在研究室活動期間登入及存取 Google Cloud。

如要完成這個研究室活動,請先確認:

  • 您可以使用標準的網際網路瀏覽器 (Chrome 瀏覽器為佳)。
注意:請使用無痕模式或私密瀏覽視窗執行此研究室。這可以防止個人帳戶和學生帳戶之間的衝突,避免個人帳戶產生額外費用。
  • 是時候完成研究室活動了!別忘了,活動一開始將無法暫停。
注意:如果您擁有個人 Google Cloud 帳戶或專案,請勿用於本研究室,以免產生額外費用。

如何開始研究室及登入 Google Cloud 控制台

  1. 按一下「Start Lab」(開始研究室) 按鈕。如果研究室會產生費用,畫面中會出現選擇付款方式的彈出式視窗。左側的「Lab Details」窗格會顯示下列項目:

    • 「Open Google Cloud console」按鈕
    • 剩餘時間
    • 必須在這個研究室中使用的暫時憑證
    • 完成這個實驗室所需的其他資訊 (如有)
  2. 點選「Open Google Cloud console」;如果使用 Chrome 瀏覽器,也能按一下滑鼠右鍵,然後選取「在無痕式視窗中開啟連結」

    接著,實驗室會啟動相關資源並開啟另一個分頁,當中顯示「登入」頁面。

    提示:您可以在不同的視窗中並排開啟分頁。

    注意:如果頁面中顯示「選擇帳戶」對話方塊,請點選「使用其他帳戶」
  3. 如有必要,請將下方的 Username 貼到「登入」對話方塊。

    {{{user_0.username | "Username"}}}

    您也可以在「Lab Details」窗格找到 Username

  4. 點選「下一步」

  5. 複製下方的 Password,並貼到「歡迎使用」對話方塊。

    {{{user_0.password | "Password"}}}

    您也可以在「Lab Details」窗格找到 Password

  6. 點選「下一步」

    重要事項:請務必使用實驗室提供的憑證,而非自己的 Google Cloud 帳戶憑證。 注意:如果使用自己的 Google Cloud 帳戶來進行這個實驗室,可能會產生額外費用。
  7. 按過後續的所有頁面:

    • 接受條款及細則。
    • 由於這是臨時帳戶,請勿新增救援選項或雙重驗證機制。
    • 請勿申請免費試用。

Google Cloud 控制台稍後會在這個分頁開啟。

注意:如要查看列出 Google Cloud 產品和服務的選單,請點選左上角的「導覽選單」「導覽選單」圖示

啟動 Cloud Shell

Cloud Shell 是搭載多項開發工具的虛擬機器,提供永久的 5 GB 主目錄,而且在 Google Cloud 中運作。Cloud Shell 提供指令列存取權,方便您使用 Google Cloud 資源。

  1. 點按 Google Cloud 控制台上方的「啟用 Cloud Shell」圖示 「啟動 Cloud Shell」圖示

連線完成即代表已通過驗證,且專案已設為您的 PROJECT_ID。輸出內容中有一行宣告本工作階段 PROJECT_ID 的文字:

您在本工作階段中的 Cloud Platform 專案會設為「YOUR_PROJECT_ID」

gcloud 是 Google Cloud 的指令列工具,已預先安裝於 Cloud Shell,並支援 Tab 鍵自動完成功能。

  1. (選用) 您可以執行下列指令來列出使用中的帳戶:
gcloud auth list
  1. 點按「授權」

  2. 輸出畫面應如下所示:

輸出內容:

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (選用) 您可以使用下列指令來列出專案 ID:
gcloud config list project

輸出內容:

[core] project = <project_ID>

輸出內容範例:

[core] project = qwiklabs-gcp-44776a13dea667a6 附註:如需有關 gcloud 的完整說明,請前往 Google Cloud 並參閱「gcloud CLI overview guide」(gcloud CLI 總覽指南)。

工作 1:建立虛擬環境

Python 虛擬環境可用來獨立安裝套件,將其與系統區隔開來。

  1. 安裝 virtualenv 環境:
sudo apt-get install -y virtualenv
  1. 建構虛擬環境:
python3 -m venv venv
  1. 啟用虛擬環境:
source venv/bin/activate

工作 2:安裝用戶端程式庫

  1. 執行下列指令來安裝用戶端程式庫:
pip install --upgrade google-cloud-pubsub
  1. 複製 GitHub 存放區來取得程式碼範例:
git clone https://github.com/googleapis/python-pubsub.git
  1. 請前往以下目錄:
cd python-pubsub/samples/snippets

工作 3:Pub/Sub - 基本知識

Pub/Sub 是非同步的全域訊息服務。Pub/Sub 中常看到的三個術語為:「topic」(主題)、「publishing」(發布) 和「subscribing」(訂閱)。

主題是一個共用字串,可讓應用程式透過共同執行緒連結至另一個應用程式。

發布端將訊息推送 (或發布) 至 Pub/Sub 主題,然後訂閱端會在該執行緒建立一個「訂閱項目」,並從主題提取訊息,或設定 Webhook 來推送訂閱項目。每位訂閱者皆須在設定時限內確認每則訊息。

總結來說,發布者會建立並傳送訊息至主題,訂閱者會建立對主題的訂閱項目來接收訊息。

Google Cloud 中的 Pub/Sub

Pub/Sub 服務預先安裝在 Cloud Shell 中,您不必進行任何安裝或設定即可開始使用。在本研究室中,您將使用 Python 建立主題和訂閱端,然後查看訊息。同時,您要使用 gcloud 指令將訊息發布至主題。

工作 4:建立主題

如要將資料發布至 Pub/Sub,請建立主題,然後設定主題的發布端。

  1. 在 Cloud Shell 中,您的專案 ID 應會自動儲存於環境變數 GOOGLE_CLOUD_PROJECT
echo $GOOGLE_CLOUD_PROJECT
  1. 請確認輸出結果與「連線詳細資料」中的專案 ID 相同。

指令碼 publisher.py 會顯示如何透過 Cloud Pub/Sub API 在主題上執行基本作業。查看發布者指令碼內容:

cat publisher.py 注意:您也可以使用安裝在 Cloud Shell 上的殼層編輯器 (例如 nano 或 vim),或 Cloud Shell 程式碼編輯器來查看 python-pubsub/samples/snippets/publisher.py
  1. 取得發布者指令碼相關資訊:
python publisher.py -h

輸出內容範例:

usage: publisher.py [-h] project {list,create,delete,publish,publish-with-custom-attributes,publish-with-futures,publish-with-error-handler,publish-with-batch-settings} ... This application demonstrates how to perform basic operations on topics with the Cloud Pub/Sub API. For more information, see the README.md under /pubsub and the documentation at https://cloud.google.com/pubsub/docs. positional arguments: project Your Google Cloud project ID {list,create,delete,publish,publish-with-custom-attributes,publish-with-futures,publish-with-error-handler,publish-with-batch-settings} list Lists all Pub/Sub topics in the given project. create Create a new Pub/Sub topic. delete Deletes an existing Pub/Sub topic. publish Publishes multiple messages to a Pub/Sub topic. publish-with-custom-attributes Publishes multiple messages with custom attributes to a Pub/Sub topic. publish-with-futures Publishes multiple messages to a Pub/Sub topic and prints their message IDs. publish-with-error-handler Publishes multiple messages to a Pub/Sub topic with an error handler. publish-with-batch-settings Publishes multiple messages to a Pub/Sub topic with batch settings. optional arguments: -h, --help show this help message and exit
  1. 執行發布者指令碼來建立 Pub/Sub 主題:
python publisher.py $GOOGLE_CLOUD_PROJECT create MyTopic

輸出內容範例:

Topic created: name: "projects/qwiklabs-gcp-fe27729bc161fb22/topics/MyTopic"

測試已完成的工作

請點選「Check my progress」 確認工作已完成。如果已成功建立 Cloud Pub/Sub 主題,就會看到評估分數。

建立主題。
  1. 這個指令會傳回指定專案中的完整 Pub/Sub 主題清單:
python publisher.py $GOOGLE_CLOUD_PROJECT list

輸出內容範例:

name: "projects/qwiklabs-gcp-fe27729bc161fb22/topics/MyTopic"

您也可以在 Cloud 控制台中查看剛建立的主題。

  1. 請依序前往「導覽選單」>「Pub/Sub」>「主題」。

您會看到 MyTopic

工作 5:建立訂閱項目

  1. 使用 subscriber.py 指令碼建立主題的 Pub/Sub 訂閱項目:
python subscriber.py $GOOGLE_CLOUD_PROJECT create MyTopic MySub

測試已完成的工作

請點選「Check my progress」 確認工作已完成。如果已成功建立 Cloud Pub/Sub 訂閱項目,就會看到評估分數。

建立訂閱項目。
  1. 這個指令會傳回指定專案中的訂閱者清單:
python subscriber.py $GOOGLE_CLOUD_PROJECT list-in-project

由於您只有建立一個訂閱項目,因此只會看到這個項目。

輸出內容範例:

projects/qwiklabs-gcp-7877af129f04d8b3/subscriptions/MySub
  1. 在控制台中查看剛建立的訂閱項目。在左側窗格中,按一下「訂閱項目」。您會看到訂閱項目名稱及其他詳細資料。

  2. 取得 subscriber 指令碼相關資訊:

python subscriber.py -h

輸出內容:

usage: subscriber.py [-h] project {list_in_topic,list_in_project,create,create-push,delete,update,receive,receive-custom-attributes,receive-flow-control,receive-synchronously,listen_for_errors} ... This application demonstrates how to perform basic operations on subscriptions with the Cloud Pub/Sub API. For more information, see the README.md under /pubsub and the documentation at https://cloud.google.com/pubsub/docs. positional arguments: project Your Google Cloud project ID {list_in_topic,list_in_project,create,create-push,delete,update,receive,receive-custom-attributes,receive-flow-control,receive-synchronously,listen_for_errors} list_in_topic Lists all subscriptions for a given topic. list_in_project Lists all subscriptions in the current project. create Create a new pull subscription on the given topic. create-push Create a new push subscription on the given topic. delete Deletes an existing Pub/Sub topic. update Updates an existing Pub/Sub subscription's push endpoint URL. Note that certain properties of a subscription, such as its topic, are not modifiable. receive Receives messages from a pull subscription. receive-custom-attributes Receives messages from a pull subscription. receive-flow-control Receives messages from a pull subscription with flow control. receive-synchronously Pulling messages synchronously. listen_for_errors Receives messages and catches errors from a pull subscription. optional arguments: -h, --help show this help message and exit

工作 6:發布訊息

現在您已設定 MyTopic (主題) 和 MyTopic (MySub) 訂閱項目,請試著使用 gcloud 指令將訊息發布至 MyTopic

  1. 將「Hello」訊息發布至 MyTopic
gcloud pubsub topics publish MyTopic --message "Hello"
  1. 執行下列指令,再對 MyTopic 多發布幾則訊息 (將 <YOUR NAME> 和 <FOOD> 分別取代為您的名字及喜歡的食物):
gcloud pubsub topics publish MyTopic --message "Publisher's name is <YOUR NAME>" gcloud pubsub topics publish MyTopic --message "Publisher likes to eat <FOOD>" gcloud pubsub topics publish MyTopic --message "Publisher thinks Pub/Sub is awesome"

工作 7:查看訊息

現在您已將訊息發布至 MyTopic,請使用 MySub 提取並查看訊息。

  1. 使用 MySub 從 MyTopic 中提取訊息:
python subscriber.py $GOOGLE_CLOUD_PROJECT receive MySub

輸出內容範例:

Listening for messages on projects/qwiklabs-gcp-7877af129f04d8b3/subscriptions/MySub Received message: Message { data: 'Publisher thinks Pub/Sub is awesome' attributes: {} } Received message: Message { data: 'Hello' attributes: {} } Received message: Message { data: "Publisher's name is Harry" attributes: {} } Received message: Message { data: 'Publisher likes to eat cheese' attributes: {} }
  1. 按下 Ctrl + C 鍵即可停止監聽。

工作 8:測試您的瞭解程度

完成下列選擇題能加深您的印象,更清楚本研究室介紹的概念,請盡您所能回答。

恭喜!

您已使用 Python 建立 Pub/Sub 主題、發布至主題、建立訂閱項目,然後使用了該主題中的訂閱項目提取資料。

後續步驟/瞭解詳情

Pub/Sub 能與 Pub/Sub Lite 相輔相成,以可預測的流量模式提供訊息系統可用區服務。如果您每秒發布 1 MiB 至 1 GiB 的訊息,可選擇使用 Pub/Sub Lite。這項產品能讓您用低成本擷取大量事件。透過這個研究室試用 Pub/Sub Lite:

這個研究室屬於 Qwik Start 研究室系列,旨在帶您一窺 Google Cloud 的眾多功能。歡迎在「Google Cloud Skills Boost 目錄」中搜尋「Qwik Start」,看看接下來要參加哪個研究室!

Google Cloud 教育訓練與認證

協助您瞭解如何充分運用 Google Cloud 的技術。我們的課程會介紹專業技能和最佳做法,讓您可以快速掌握要領並持續進修。我們提供從基本到進階等級的訓練課程,並有隨選、線上和虛擬課程等選項,方便您抽空參加。認證可協助您驗證及證明自己在 Google Cloud 技術方面的技能和專業知識。

使用手冊上次更新日期:2024 年 2 月 13 日

研究室上次測試日期:2023 年 9 月 22 日

Copyright 2025 Google LLC 保留所有權利。Google 和 Google 標誌是 Google LLC 的商標,其他公司和產品名稱則有可能是其關聯公司的商標。

Before you begin

  1. Labs create a Google Cloud project and resources for a fixed time
  2. Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
  3. On the top left of your screen, click Start lab to begin

Use private browsing

  1. Copy the provided Username and Password for the lab
  2. Click Open console in private mode

Sign in to the Console

  1. Sign in using your lab credentials. Using other credentials might cause errors or incur charges.
  2. Accept the terms, and skip the recovery resource page
  3. Don't click End lab unless you've finished the lab or want to restart it, as it will clear your work and remove the project

此内容目前不可用

一旦可用,我们会通过电子邮件告知您

太好了!

一旦可用,我们会通过电子邮件告知您

One lab at a time

Confirm to end all existing labs and start this one

Setup your console before you begin

Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.