Membuat kumpulan pekerja Cloud Run untuk Langganan Pub/Sub Berbasis Pull

1. Pengantar

Ringkasan

Worker pool adalah resource Cloud Run yang dirancang khusus untuk workload non-permintaan, seperti pull queue. Perhatikan bahwa gabungan worker tidak memiliki fitur berikut:

  • Tidak ada endpoint/URL
  • Tidak ada persyaratan agar container yang di-deploy memproses permintaan di port
  • Tidak ada penskalaan otomatis

Dalam codelab ini, Anda akan membuat kumpulan pekerja yang akan terus-menerus mengambil pesan dari langganan pull Pub/Sub. Anda dapat mempelajari lebih lanjut langganan pull Pub/Sub dalam dokumentasi dan dalam contoh kode ini.

Yang akan Anda pelajari

  • Cara membuat dan men-deploy ke kumpulan pekerja Cloud Run
  • Cara mengambil pesan dari langganan Pub/Sub berbasis Pull

2. Penyiapan dan Persyaratan

Pertama, tetapkan variabel lingkungan untuk codelab ini:

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

Selanjutnya, konfigurasikan gcloud untuk menggunakan project ID Anda

gcloud config set project $PROJECT_ID

Sebelum Anda dapat mulai menggunakan codelab ini, aktifkan API berikut dengan menjalankan:

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

Buat akun layanan dengan menjalankan:

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

Terakhir, beri akun layanan Cloud Run Anda akses ke PubSub:

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

3. Buat kumpulan pekerja Cloud Run

Pertama, buat direktori untuk kode pool worker Anda:

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

Selanjutnya, buat file bernama 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"
    }
}

Sekarang, buat file bernama 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. Men-deploy Kumpulan Pekerja

Buat kumpulan pekerja Cloud Run dengan menjalankan perintah berikut:

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

Perintah ini membangun image dari sumber dan men-deploy tugas. Proses ini akan memerlukan waktu beberapa menit.

5. Memublikasikan pesan ke PubSub

Buat topik PubSub

gcloud pubsub topics create $TOPIC

Buat langganan pull PubSub

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

Jalankan perintah berikut untuk memublikasikan pesan ke topik PubSub Anda.

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

Periksa log untuk kumpulan pekerja Anda

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

Anda akan melihat Hello Worker Pools di log.

6. Menghapus kumpulan pekerja

Karena kumpulan pekerja berjalan terus-menerus, Anda harus menghapus kumpulan pekerja.

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

7. Selamat!

Selamat, Anda telah menyelesaikan codelab.

Sebaiknya tinjau dokumentasi Cloud Run.

Yang telah kita bahas

  • Cara membuat dan men-deploy ke kumpulan pekerja Cloud Run
  • Cara mengambil pesan dari langganan Pub/Sub berbasis Pull

8. Pembersihan

Untuk menghapus kumpulan pekerja Cloud Run, buka Konsol Cloud Run di https://console.cloud.google.com/run, lalu hapus kumpulan pekerja codelab-workers-pubsub.

Untuk menghapus seluruh project, buka Manage Resources, pilih project yang Anda buat di Langkah 2, lalu pilih Hapus. Jika menghapus project, Anda harus mengubah project di Cloud SDK. Anda dapat melihat daftar semua project yang tersedia dengan menjalankan gcloud projects list.