arrow_back

Pub/Sub Lite: Qwik Start

参加 ログイン
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

Pub/Sub Lite: Qwik Start

Lab 30分 universal_currency_alt クレジット: 1 show_chart 入門
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

GSP832

Google Cloud self-paced labs logo

Overview

Complementing Pub/Sub, Pub/Sub Lite is a zonal service for messaging systems with predictable traffic patterns. If you publish 1 MiB-1 GiB of messages per second, Pub/Sub Lite is a low cost option for high-volume event ingestion.

Publishers send messages to Lite topics and subscribers receive messages from Lite subscriptions. Lite topics and Lite subscriptions are zonal resources that must be in the same Cloud project and zone. For a list of zones that Pub/Sub Lite supports, refer to Pub/Sub Lite locations.

In this lab you will learn how to:

  • Create Lite topics and Lite subscriptions using the Cloud Console.
  • Send and receive messages using the Pub/Sub Lite client library for Python.

Setup

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left. Navigation menu icon

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Set your project

gcloud config set project {{{project_0.project_id | "filled in at lab start"}}}

Enable the Pub/Sub Lite API

  1. In the Cloud Console, navigate to APIs & Services > Library.

The navigation path to the Library option

  1. Start typing "pub/sub" in the Search bar, then select the Pub/Sub Lite tile.

The highlighted Pub/Sub Lite tile in the Search results

  1. Now click the Enable button.

  2. In Cloud Shell, run the following to install the the Python client library:

pip3 install --upgrade google-cloud-pubsublite

Task 1. Create a Lite Topic

To create a Lite topic with the Cloud Console, follow these steps:

  1. In the Cloud Console, go to Navigation menu > Pub/Sub > Lite Topics page.

  2. Click Create Lite topic.

  3. Select Regional Lite topic to choose the region and then select Zonal Lite topic to choose the zone (this lab uses ), then click Continue.

  4. In the Name section, enter my-lite-topic as the Lite topic ID. The Lite topic name includes the Lite topic ID, the zone, and the project number.

  5. Click Continue.

  6. Make sure to uncheck Attach to a reservation checkbox.

  7. Click Create.

Click Check my progress to verify the objective. Create a Lite Topic

Task 2. Create a Lite Subscription

To create a Lite subscription with Cloud Console, follow these steps:

  1. Click on Lite Subscriptions in the left menu.
  2. Click Create Lite subscription.
  3. In the Lite subscription ID field, enter my-lite-subscription.
  4. In Select a Lite resources select a Lite topic to receive messages, you created in the last step.
  5. In the Delivery requirement section, select Deliver messages after stored.
  6. Click Create.

The Lite subscription is in the same zone as the Lite topic.

Click Check my progress to verify the objective. Create a Lite Subscription

Task 3. Send messages

Send messages to the Lite topic using the following publisher application. Using the Cloud Shell Editor or the editor of your choice, create a file called send_messages.py and add the following script, then:

  1. Uncomment all steps in the TODO section.

  2. Replace project_number with the project number you can see in the Lite topic and subscription name in the Console. The project number highlighted on the Lite subscription details page

  3. If you used a different cloud_region and zone_id, update with your information:

from google.cloud.pubsublite.cloudpubsub import PublisherClient from google.cloud.pubsublite.types import ( CloudRegion, CloudZone, MessageMetadata, TopicPath, ) # TODO(developer): # project_number = 1122334455 # cloud_region = "{{{project_0.default_region | "filled in at lab start"}}}" # zone_id = "a" # topic_id = "my-lite-topic" # num_messages = 100 location = CloudZone(CloudRegion(cloud_region), zone_id) topic_path = TopicPath(project_number, location, topic_id) # PublisherClient() must be used in a `with` block or have __enter__() called before use. with PublisherClient() as publisher_client: data = "Hello world!" api_future = publisher_client.publish(topic_path, data.encode("utf-8")) # result() blocks. To resolve API futures asynchronously, use add_done_callback(). message_id = api_future.result() publish_metadata = MessageMetadata.decode(message_id) print( f"Published a message to partition {publish_metadata.partition.value} and offset {publish_metadata.cursor.offset}." )

The publisher sends 100 messages to a Lite topic and prints the number of messages that the Pub/Sub Lite service receives.

Task 4. Receive messages

Receive messages from the Lite subscription using the following subscriber application. Using the Cloud Shell Editor or the editor of your choice, create a file called receive_messages.py and add the following script, then

  1. Uncomment all steps in the TODO section.

  2. Replace project_number with the Project number you can see in the Lite topic and subscription name in the Console. The project number highlighted on the Lite subscription details page

  3. If you used a different cloud_region and zone_id, update with your information:

from concurrent.futures._base import TimeoutError from google.cloud.pubsublite.cloudpubsub import SubscriberClient from google.cloud.pubsublite.types import ( CloudRegion, CloudZone, FlowControlSettings, SubscriptionPath, ) # TODO(developer): # project_number = 1122334455 # cloud_region = "{{{project_0.default_region | "filled in at lab start"}}}" # zone_id = "a" # subscription_id = "my-lite-subscription" # timeout = 90 location = CloudZone(CloudRegion(cloud_region), zone_id) subscription_path = SubscriptionPath(project_number, location, subscription_id) # Configure when to pause the message stream for more incoming messages based on the # maximum size or number of messages that a single-partition subscriber has received, # whichever condition is met first. per_partition_flow_control_settings = FlowControlSettings( # 1,000 outstanding messages. Must be >0. messages_outstanding=1000, # 10 MiB. Must be greater than the allowed size of the largest message (1 MiB). bytes_outstanding=10 * 1024 * 1024, ) def callback(message): message_data = message.data.decode("utf-8") print(f"Received {message_data} of ordering key {message.ordering_key}.") message.ack() # SubscriberClient() must be used in a `with` block or have __enter__() called before use. with SubscriberClient() as subscriber_client: streaming_pull_future = subscriber_client.subscribe( subscription_path, callback=callback, per_partition_flow_control_settings=per_partition_flow_control_settings, ) print(f"Listening for messages on {str(subscription_path)}...") try: streaming_pull_future.result(timeout=timeout) except TimeoutError or KeyboardInterrupt: streaming_pull_future.cancel() assert streaming_pull_future.done()

After the subscriber receives a message, the subscriber prints the message ID and the message data.

  1. Now run both scripts:
python3 send_messages.py python3 receive_messages.py

You will see output in Cloud Shell that looks like this:

Received Hello world! of ordering key .

You will also be able to monitor activity on the Lite Topics and Lite Subscriptions pages in the Cloud Console.

Task 5. Clean up

Although all resources will be destroyed when you end this lab, it's good practice to clean up resources you don't need to avoid charges.

  1. In the Cloud Console, go to the Lite Topics page.
  2. Click my-lite-topic.
  3. On the Lite topic details page, click Delete.
  4. In the field that appears, type delete to confirm that you want to delete the Lite topic.
  5. Click Delete.

Congratulations!

Now you can use Pub/Sub Lite to create topics and subscriptions, and send and receive messages.

Finish your quest

This self-paced lab is part of the Baseline: Infrastructure quest. A quest is a series of related labs that form a learning path. Completing this quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in this quest and get immediate completion credit if you've taken this lab. Refer to the Google Cloud Skills Boost catalog for all available quests.

Next steps / Learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated May 12, 2023

Lab Last Tested April 25, 2022

Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.