為以提取為基礎的 Pub/Sub 訂閱項目建立 Cloud Run 工作站集區

1. 簡介

總覽

工作站集區是專為非要求工作負載 (例如提取佇列) 設計的 Cloud Run 資源。請注意,工作站集區不具備下列功能:

  • 沒有端點/網址
  • 部署的容器不必在通訊埠監聽要求
  • 不自動調整資源配置

在本程式碼研究室中,您將建立工作站集區,持續從 Pub/Sub 提取訂閱項目擷取訊息。如要進一步瞭解 Pub/Sub 提取訂閱項目,請參閱說明文件這個程式碼範例

課程內容

  • 如何建立應用程式並部署至 Cloud Run 工作站集區
  • 如何從以提取為基礎的 Pub/Sub 訂閱項目擷取訊息

2. 設定和需求

首先,請為本程式碼研究室設定環境變數:

export PROJECT_ID=<your_project_id>
export REGION=<your_region>

export WORKER_POOL_NAME=codelab-workers-pubsub
export SERVICE_ACCOUNT=worker-pools-sa
export SERVICE_ACCOUNT_EMAIL=${SERVICE_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com
export TOPIC=pull-pubsub-topic

接著,設定 gcloud 以使用您的專案 ID

gcloud config set project $PROJECT_ID

開始使用本程式碼研究室前,請先執行下列指令,啟用下列 API:

gcloud services enable run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com \
    pubsub.googleapis.com

執行下列指令來建立服務帳戶:

gcloud iam service-accounts create ${SERVICE_ACCOUNT} \
  --display-name="Service account for worker pool codelab"

最後,授予 Cloud Run 服務帳戶 Pub/Sub 的存取權:

gcloud projects add-iam-policy-binding $PROJECT_ID \
    --member serviceAccount:$SERVICE_ACCOUNT_EMAIL \
    --role='roles/pubsub.admin'

3. 建立 Cloud Run 工作站集區

首先,請為工作站集區程式碼建立目錄:

mkdir codelab-worker-pools
cd codelab-worker-pools

接著,建立名為 package.json 的檔案。

{
    "name": "codelab-worker-pools",
    "version": "1.0.0",
    "description": "A codelab example of a Cloud Run worker pool retrieving messages from a Pull-based PubSub subscription",
    "main": "index.js",
    "scripts": {
        "start": "node index.js"
    },
    "engines": {
        "node": ">=22.0.0"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "@google-cloud/pubsub": "^5.1.0"
    }
}

現在,請建立名為 index.js 的檔案:

'use strict';

const subscriptionNameOrId = 'pull-pubsub-topic';

const { PubSub } = require('@google-cloud/pubsub');

// Creates a Pub/Sub client; cache this for further use.
const pubSubClient = new PubSub();

// References an existing subscription.
const subscription = pubSubClient.subscription(subscriptionNameOrId);

// This function is called when a shutdown signal is received.
const handleShutdown = async (signal) => {
  console.log(`\n${signal} signal caught. Shutting down gracefully...`);

  try {
    // 1. Stop listening for new messages. The `close()` method returns a Promise.
    console.log('Closing Pub/Sub subscription...');
    await subscription.close();
    console.log('Pub/Sub subscription closed.');

    // 2. Add any other cleanup logic here, like closing database connections.

  } catch (err) {
    console.error('Error during graceful shutdown:', err);
  } finally {
    console.log('Worker Pool exited.');
    process.exit(0);
  }
};

// Listen for termination signals.
// SIGINT handles Ctrl+C locally.
// SIGTERM handles signals from services like Cloud Run.
process.on('SIGINT', () => handleShutdown('SIGINT'));
process.on('SIGTERM', () => handleShutdown('SIGTERM'));

// ------------------ Pub/Sub Message Handling ------------------

// Create an event handler to process incoming messages.
const messageHandler = message => {
  console.log(`Received message ${message.id}:`);
  console.log(`\tData: ${message.data}`);
  console.log(`\tAttributes: ${JSON.stringify(message.attributes)}`);

  // Ack the message so it is not sent again.
  message.ack();
};

// Register the message handler and listen for messages.
subscription.on('message', messageHandler);

console.log(
  `Worker started. Listening for messages on "${subscriptionNameOrId}".`
);
console.log('If running locally, press Ctrl+C to quit.');

// The application will now listen for messages indefinitely until a shutdown
// signal is received.

4. 部署工作站集區

執行下列指令,建立 Cloud Run 工作站集區:

gcloud beta run worker-pools deploy $WORKER_POOL_NAME --region=$REGION --source .

這個指令會從來源建構映像檔,並部署作業。這項作業會在幾分鐘內完成。

5. 將訊息發布至 Pub/Sub

建立 Pub/Sub 主題

gcloud pubsub topics create $TOPIC

建立 PubSub 提取訂閱項目

gcloud pubsub subscriptions create codelab-subscription --topic=$TOPIC

執行下列指令,將訊息發布至 Pub/Sub 主題。

gcloud pubsub topics publish $TOPIC --message "Hello Worker Pools"

檢查工作站集區的記錄

gcloud logging read 'resource.type="cloud_run_worker_pool" AND resource.labels.worker_pool_name="'$WORKER_POOL_NAME'" AND resource.labels.location="'$REGION'"' --limit 10

記錄中應會顯示 Hello Worker Pools

6. 刪除工作站集區

由於工作站集區會持續執行,因此您應刪除工作站集區。

gcloud beta run worker-pools delete $WORKER_POOL_NAME --region $REGION

7. 恭喜!

恭喜您完成本程式碼研究室!

建議參閱 Cloud Run 說明文件。

涵蓋內容

  • 如何建立應用程式並部署至 Cloud Run 工作站集區
  • 如何從以提取為基礎的 Pub/Sub 訂閱項目擷取訊息

8. 清除

如要刪除 Cloud Run 工作站集區,請前往 Cloud Run Cloud 控制台 (https://console.cloud.google.com/run),然後刪除 codelab-workers-pubsub 工作站集區。

如要刪除整個專案,請前往「管理資源」,選取您在步驟 2 中建立的專案,然後選擇「刪除」。刪除專案後,您必須在 Cloud SDK 中變更專案。如要查看所有可用專案的清單,請執行 gcloud projects list