הדרכה בנושא Cloud Pub/Sub (דור ראשון)

במדריך הפשוט הזה נסביר איך לכתוב ולפרוס פונקציית Cloud Run מבוססת-אירועים עם טריגר Pub/Sub, ואיך להפעיל אותה.

אם אתם חדשים ב-Pub/Sub ורוצים לקבל מידע נוסף, תוכלו לעיין בתיעוד של Pub/Sub, ובמיוחד במאמר בנושא ניהול נושאים ומינויים. במאמר בנושא טריגרים ב-Pub/Sub מופיעה סקירה כללית על עבודה עם נושאים ומינויים ב-Pub/Sub בפונקציות Cloud Run.

אם אתם מחפשים דוגמאות קוד לשימוש ב-Pub/Sub עצמו, אתם יכולים להיעזר בדפדפן הדוגמאות.

מטרות

עלויות

במסמך הזה משתמשים ברכיבים הבאים של Google Cloud, והשימוש בהם כרוך בתשלום:

  • Cloud Run functions
  • Pub/Sub

כדי להעריך את ההוצאות בהתאם לתחזית השימוש שלכם, אתם יכולים להיעזר במחשבון העלויות.

משתמשים חדשים של Google Cloud ? יכול להיות שאתם זכאים לתקופת ניסיון בחינם.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Pub/Sub APIs.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  5. התקינו את ה-CLI של Google Cloud.

  6. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  7. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Functions and Cloud Pub/Sub APIs.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  11. התקינו את ה-CLI של Google Cloud.

  12. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  13. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  14. אם כבר התקנתם את ה-CLI של gcloud, מריצים את הפקודה הבאה כדי לעדכן אותו:

    gcloud components update
  15. מכינים את סביבת הפיתוח.

הכנת הבקשה

  1. משכפלים את מאגר האפליקציה לדוגמה ומעבירים אותו למכונה המקומית:

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    אפשרות נוספת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    אפשרות נוספת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

    המשך

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    אפשרות נוספת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    אפשרות נוספת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    אפשרות נוספת היא להוריד את הדוגמה כקובץ ZIP ולחלץ אותה.

  2. עוברים לספרייה שמכילה את הקוד לדוגמה של פונקציות Cloud Run לגישה ל-Pub/Sub:

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/hello-pubsub/

    Ruby

    cd ruby-docs-samples/functions/helloworld/pubsub/

  3. כדאי לעיין בקוד לדוגמה:

    Node.js

    /**
     * Background Cloud Function to be triggered by Pub/Sub.
     * This function is exported by index.js, and executed when
     * the trigger topic receives a message.
     *
     * @param {object} message The Pub/Sub message.
     * @param {object} context The event metadata.
     */
    exports.helloPubSub = (message, context) => {
      const name = message.data
        ? Buffer.from(message.data, 'base64').toString()
        : 'World';
    
      console.log(`Hello, ${name}!`);
    };

    Python

    def hello_pubsub(event, context):
        """Background Cloud Function to be triggered by Pub/Sub.
        Args:
             event (dict):  The dictionary with data specific to this type of
                            event. The `@type` field maps to
                             `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
                            The `data` field maps to the PubsubMessage data
                            in a base64-encoded string. The `attributes` field maps
                            to the PubsubMessage attributes if any is present.
             context (google.cloud.functions.Context): Metadata of triggering event
                            including `event_id` which maps to the PubsubMessage
                            messageId, `timestamp` which maps to the PubsubMessage
                            publishTime, `event_type` which maps to
                            `google.pubsub.topic.publish`, and `resource` which is
                            a dictionary that describes the service API endpoint
                            pubsub.googleapis.com, the triggering topic's name, and
                            the triggering event type
                            `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
        Returns:
            None. The output is written to Cloud Logging.
        """
        import base64
    
        print(
            """This Function was triggered by messageId {} published at {} to {}
        """.format(
                context.event_id, context.timestamp, context.resource["name"]
            )
        )
    
        if "data" in event:
            name = base64.b64decode(event["data"]).decode("utf-8")
        else:
            name = "World"
        print(f"Hello {name}!")
    
    

    המשך

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"context"
    	"log"
    )
    
    // PubSubMessage is the payload of a Pub/Sub event.
    // See the documentation for more details:
    // https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
    type PubSubMessage struct {
    	Data []byte `json:"data"`
    }
    
    // HelloPubSub consumes a Pub/Sub message.
    func HelloPubSub(ctx context.Context, m PubSubMessage) error {
    	name := string(m.Data) // Automatically decoded from base64.
    	if name == "" {
    		name = "World"
    	}
    	log.Printf("Hello, %s!", name)
    	return nil
    }
    

    Java

    
    import com.google.cloud.functions.BackgroundFunction;
    import com.google.cloud.functions.Context;
    import functions.eventpojos.PubsubMessage;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class HelloPubSub implements BackgroundFunction<PubsubMessage> {
      private static final Logger logger = Logger.getLogger(HelloPubSub.class.getName());
    
      @Override
      public void accept(PubsubMessage message, Context context) {
        String name = "world";
        if (message != null && message.getData() != null) {
          name = new String(
              Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
              StandardCharsets.UTF_8);
        }
        logger.info(String.format("Hello %s!", name));
        return;
      }
    }

    Ruby

    require "functions_framework"
    require "base64"
    
    FunctionsFramework.cloud_event "hello_pubsub" do |event|
      # The event parameter is a CloudEvents::Event::V1 object.
      # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
      name = Base64.decode64 event.data["message"]["data"] rescue "World"
    
      # A cloud_event function does not return a response, but you can log messages
      # or cause side effects such as sending additional events.
      logger.info "Hello, #{name}!"
    end

פריסת הפונקציה

כדי לפרוס את הפונקציה עם טריגר Pub/Sub, מריצים את הפקודה הבאה בספרייה שמכילה את הקוד לדוגמה (או במקרה של Java, את הקובץ pom.xml):

Node.js

gcloud functions deploy helloPubSub \
--runtime nodejs22 \
--trigger-topic YOUR_TOPIC_NAME

משתמשים בדגל --runtime כדי לציין את מזהה סביבת זמן הריצה של גרסת Node.js נתמכת להרצת הפונקציה.

Python

gcloud functions deploy hello_pubsub \
--runtime python312 \
--trigger-topic YOUR_TOPIC_NAME

משתמשים בדגל --runtime כדי לציין את מזהה זמן הריצה של גרסת Python נתמכת להרצת הפונקציה.

המשך

gcloud functions deploy HelloPubSub \
--runtime go121 \
--trigger-topic YOUR_TOPIC_NAME

כדי לציין את מזהה זמן הריצה של גרסת Go נתמכת להרצת הפונקציה, משתמשים בדגל --runtime.

Java

gcloud functions deploy java-pubsub-function \
--entry-point functions.HelloPubSub \
--runtime java17 \
--memory 512MB \
--trigger-topic YOUR_TOPIC_NAME

משתמשים בדגל --runtime כדי לציין את מזהה זמן הריצה של גרסת Java נתמכת להרצת הפונקציה.

Ruby

gcloud functions deploy hello_pubsub --runtime ruby33 \
-
-trigger-topic YOUR_TOPIC_NAME

משתמשים בדגל --runtime כדי לציין את מזהה זמן הריצה של גרסת Ruby נתמכת להרצת הפונקציה.

כאשר YOUR_TOPIC_NAME הוא השם של נושא Pub/Sub שהפונקציה תירשם אליו.

אם YOUR_TOPIC_NAME עדיין לא קיים, הפקודה הזו תיצור אותו בשבילכם. אפשר גם ליצור נושא לפני שמריצים את הפקודה deploy באמצעות Google Cloud המסוף או הפקודה gcloud הבאה:

gcloud pubsub topics create YOUR_TOPIC_NAME

הפעלת הפונקציה

  1. מפרסמים הודעה בנושא Pub/Sub. בדוגמה הזו, ההודעה היא שם שהפונקציה תכלול בברכה:

    gcloud pubsub topics publish YOUR_TOPIC_NAME --message YOUR_NAME

    מחליפים את YOUR_TOPIC_NAME בשם הנושא של Pub/Sub ואת YOUR_NAME במחרוזת שרירותית.

  2. כדי לוודא שההפעלה הסתיימה, בודקים את היומנים:

    gcloud functions logs read --limit 50

אפשר גם לפרסם הודעה לנושא Pub/Sub מתוך פונקציה.

הסרת המשאבים

כדי להימנע מחיובים בחשבון Google Cloud בגלל השימוש במשאבים שנעשה במסגרת המדריך הזה, אפשר למחוק את הפרויקט שמכיל את המשאבים, או להשאיר את הפרויקט ולמחוק את המשאבים בנפרד.

מחיקת הפרויקט

הדרך הקלה ביותר לבטל את החיוב היא למחוק את הפרויקט שיצרתם בשביל המדריך.

כדי למחוק את הפרויקט:

  1. במסוף Google Cloud , נכנסים לדף Manage resources.

    כניסה לדף Manage resources

  2. ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
  3. כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.

מחיקת הפונקציה

מחיקה של פונקציות Cloud Run לא מסירה משאבים שמאוחסנים ב-Cloud Storage.

כדי למחוק את הפונקציה שיצרתם במדריך הזה, מריצים את הפקודה הבאה:

Node.js

gcloud functions delete helloPubSub 

Python

gcloud functions delete hello_pubsub 

Go

gcloud functions delete HelloPubSub 

Java

gcloud functions delete java-pubsub-function 

Ruby

gcloud functions delete hello_pubsub 

אפשר גם למחוק פונקציות Cloud Run ממסוףGoogle Cloud .