1. 소개
개요
작업자 풀은 풀 큐와 같은 요청이 아닌 워크로드를 위해 특별히 설계된 Cloud Run 리소스입니다. 작업자 풀에는 다음 기능이 없습니다.
- 엔드포인트/URL 없음
- 배포된 컨테이너가 포트에서 요청을 리슨할 필요가 없음
- 자동 확장 없음
이 Codelab에서는 Pub/Sub 풀 구독에서 메시지를 지속적으로 가져오는 작업자 풀을 만듭니다. 문서 및 이 코드 예시에서 Pub/Sub 가져오기 구독에 대해 자세히 알아볼 수 있습니다.
학습할 내용
- Cloud Run 작업자 풀을 만들고 배포하는 방법
- 가져오기 기반 Pub/Sub 구독에서 메시지를 가져오는 방법
2. 설정 및 요구사항
먼저 이 Codelab의 환경 변수를 설정합니다.
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
다음으로 프로젝트 ID를 사용하도록 gcloud를 구성합니다.
gcloud config set project $PROJECT_ID
이 Codelab을 시작하기 전에 다음을 실행하여 다음 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 서비스 계정에 PubSub에 대한 액세스 권한을 부여합니다.
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. PubSub에 메시지 게시
Pub/Sub 주제 만들기
gcloud pubsub topics create $TOPIC
PubSub 풀 구독 만들기
gcloud pubsub subscriptions create codelab-subscription --topic=$TOPIC
다음 명령어를 실행하여 PubSub 주제에 메시지를 게시합니다.
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. 축하합니다.
축하합니다. Codelab을 완료했습니다.
Cloud Run 문서를 검토하는 것이 좋습니다.
학습한 내용
- Cloud Run 작업자 풀을 만들고 배포하는 방법
- 가져오기 기반 Pub/Sub 구독에서 메시지를 가져오는 방법
8. 삭제
Cloud Run 작업자 풀을 삭제하려면 https://console.cloud.google.com/run에서 Cloud Run Cloud 콘솔로 이동하여 codelab-workers-pubsub
작업자 풀을 삭제합니다.
전체 프로젝트를 삭제하려면 리소스 관리로 이동하여 2단계에서 만든 프로젝트를 선택하고 삭제를 선택합니다. 프로젝트를 삭제하면 Cloud SDK에서 프로젝트를 변경해야 합니다. gcloud projects list
를 실행하여 사용 가능한 모든 프로젝트의 목록을 볼 수 있습니다.