새 함수를 만드는 경우 Cloud Run의
콘솔 빠른 시작을 참고하세요.
Cloud Pub/Sub(2세대)
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Cloud Functions(2세대) 및 Eventarc를 사용하여 Cloud Pub/Sub 메시지 처리
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
C#
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Go
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Java
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Node.js
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
PHP
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Python
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Ruby
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis document demonstrates how to process Cloud Pub/Sub messages using Cloud Functions (2nd Gen) and Eventarc.\u003c/p\u003e\n"],["\u003cp\u003eCode examples are provided in C#, Go, Java, Node.js, PHP, Python, and Ruby, showing how to handle Pub/Sub messages within a Cloud Function.\u003c/p\u003e\n"],["\u003cp\u003eEach code example showcases the extraction and decoding of message data from Pub/Sub messages received via CloudEvents.\u003c/p\u003e\n"],["\u003cp\u003eThe document also directs to documentation regarding authenticating to Cloud Run functions using Application Default Credentials.\u003c/p\u003e\n"],["\u003cp\u003eThe content is focused on a practical method of triggering functions from Pub/Sub with use of Eventarc, and covers a variety of programming languages.\u003c/p\u003e\n"]]],[],null,["# Cloud Pub/Sub (2nd Gen)\n\nProcess a Cloud Pub/Sub message using Cloud Functions (2nd Gen) and Eventarc\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Locally test your function](/functions/docs/running/direct)\n- [The Go Runtime](/functions/1stgendocs/concepts/go-runtime)\n- [The Go runtime](/run/docs/runtimes/go)\n- [Trigger functions from Pub/Sub using Eventarc](/run/docs/tutorials/pubsub-eventdriven)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n using CloudNative.CloudEvents;\n using Google.Cloud.Functions.Framework;\n using Google.Events.Protobuf.Cloud.PubSub.V1;\n using Microsoft.Extensions.Logging;\n using System.Threading;\n using System.Threading.Tasks;\n\n namespace HelloPubSub;\n\n public class Function : ICloudEventFunction\u003cMessagePublishedData\u003e\n {\n private readonly ILogger _logger;\n\n public Function(ILogger\u003cFunction\u003e logger) =\u003e\n _logger = logger;\n\n public Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)\n {\n string nameFromMessage = data.Message?.TextData;\n string name = string.IsNullOrEmpty(nameFromMessage) ? \"world\" : nameFromMessage;\n _logger.LogInformation(\"Hello {name}\", name);\n return Task.CompletedTask;\n }\n }\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package helloworld provides a set of Cloud Functions samples.\n package helloworld\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"log\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n \t\"github.com/cloudevents/sdk-go/v2/event\"\n )\n\n func init() {\n \tfunctions.CloudEvent(\"HelloPubSub\", helloPubSub)\n }\n\n // MessagePublishedData contains the full Pub/Sub message\n // See the documentation for more details:\n // https://cloud.google.com/eventarc/docs/cloudevents#pubsub\n type MessagePublishedData struct {\n \tMessage PubSubMessage\n }\n\n // PubSubMessage is the payload of a Pub/Sub event.\n // See the documentation for more details:\n // https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage\n type PubSubMessage struct {\n \tData []byte `json:\"data\"`\n }\n\n // helloPubSub consumes a CloudEvent message and extracts the Pub/Sub message.\n func helloPubSub(ctx context.Context, e event.Event) error {\n \tvar msg MessagePublishedData\n \tif err := e.DataAs(&msg); err != nil {\n \t\treturn fmt.Errorf(\"event.DataAs: %w\", err)\n \t}\n\n \tname := string(msg.Message.Data) // Automatically decoded from base64.\n \tif name == \"\" {\n \t\tname = \"World\"\n \t}\n \tlog.Printf(\"Hello, %s!\", name)\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.google.cloud.functions.CloudEventsFunction;\n import com.google.gson.Gson;\n import functions.eventpojos.PubSubBody;\n import io.cloudevents.CloudEvent;\n import java.nio.charset.StandardCharsets;\n import java.util.Base64;\n import java.util.logging.Logger;\n\n public class SubscribeToTopic implements CloudEventsFunction {\n private static final Logger logger = Logger.getLogger(SubscribeToTopic.class.getName());\n\n @Override\n public void accept(CloudEvent event) {\n // The Pub/Sub message is passed as the CloudEvent's data payload.\n if (event.getData() != null) {\n // Extract Cloud Event data and convert to PubSubBody\n String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);\n Gson gson = new Gson();\n PubSubBody body = gson.fromJson(cloudEventData, PubSubBody.class);\n // Retrieve and decode PubSub message data\n String encodedData = body.getMessage().getData();\n String decodedData =\n new String(Base64.getDecoder().decode(encodedData), StandardCharsets.UTF_8);\n logger.info(\"Hello, \" + decodedData + \"!\");\n }\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const functions = require('@google-cloud/functions-framework');\n\n // Register a CloudEvent callback with the Functions Framework that will\n // be executed when the Pub/Sub trigger topic receives a message.\n functions.cloudEvent('helloPubSub', cloudEvent =\u003e {\n // The Pub/Sub message is passed as the CloudEvent's data payload.\n const base64name = cloudEvent.data.message.data;\n\n const name = base64name\n ? Buffer.from(base64name, 'base64').toString()\n : 'World';\n\n console.log(`Hello, ${name}!`);\n });\n\n### PHP\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n use CloudEvents\\V1\\CloudEventInterface;\n use Google\\CloudFunctions\\FunctionsFramework;\n\n // Register the function with Functions Framework.\n // This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment\n // variable when deploying. The `FUNCTION_TARGET` environment variable should\n // match the first parameter.\n FunctionsFramework::cloudEvent('helloworldPubsub', 'helloworldPubsub');\n\n function helloworldPubsub(CloudEventInterface $event): void\n {\n $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');\n\n $cloudEventData = $event-\u003egetData();\n $pubSubData = base64_decode($cloudEventData['message']['data']);\n\n $name = $pubSubData ? htmlspecialchars($pubSubData) : 'World';\n fwrite($log, \"Hello, $name!\" . PHP_EOL);\n }\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import base64\n\n from cloudevents.http import CloudEvent\n import functions_framework\n\n\n # Triggered from a message on a Cloud Pub/Sub topic.\n @functions_framework.cloud_event\n def subscribe(cloud_event: CloudEvent) -\u003e None:\n # Print out the data from Pub/Sub, to prove that it worked\n print(\n \"Hello, \" + base64.b64decode(cloud_event.data[\"message\"][\"data\"]).decode() + \"!\"\n )\n\n### Ruby\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n require \"functions_framework\"\n require \"base64\"\n\n FunctionsFramework.cloud_event \"hello_pubsub\" do |event|\n # The event parameter is a CloudEvents::Event::V1 object.\n # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html\n name = Base64.decode64 event.data[\"message\"][\"data\"] rescue \"World\"\n\n # A cloud_event function does not return a response, but you can log messages\n # or cause side effects such as sending additional events.\n logger.info \"Hello, #{name}!\"\n end\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]