선택한 전송 모드로 라이트 구독을 만듭니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
Go
Pub/Sub Lite에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
import (
"context"
"fmt"
"io"
"cloud.google.com/go/pubsublite"
)
func createSubscription(w io.Writer, projectID, region, location, topicID, subID string) error {
// projectID := "my-project-id"
// region := "us-central1"
// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
// location := "us-central1"
// NOTE: topic and subscription must be in the same region/zone (e.g. "us-central1-a")
// topicID := "my-topic"
// subID := "my-subscription"
ctx := context.Background()
client, err := pubsublite.NewAdminClient(ctx, region)
if err != nil {
return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
}
defer client.Close()
sub, err := client.CreateSubscription(ctx, pubsublite.SubscriptionConfig{
Name: fmt.Sprintf("projects/%s/locations/%s/subscriptions/%s", projectID, location, subID),
Topic: fmt.Sprintf("projects/%s/locations/%s/topics/%s", projectID, location, topicID),
DeliveryRequirement: pubsublite.DeliverImmediately, // can also be DeliverAfterStored
})
if err != nil {
return fmt.Errorf("client.CreateSubscription got err: %w", err)
}
fmt.Fprintf(w, "Created subscription: %s\n", sub.Name)
return nil
}
Java
Pub/Sub Lite에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
import com.google.api.gax.rpc.AlreadyExistsException;
import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.AdminClientSettings;
import com.google.cloud.pubsublite.CloudRegion;
import com.google.cloud.pubsublite.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.SubscriptionName;
import com.google.cloud.pubsublite.SubscriptionPath;
import com.google.cloud.pubsublite.TopicName;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.proto.Subscription;
import com.google.cloud.pubsublite.proto.Subscription.DeliveryConfig;
import com.google.cloud.pubsublite.proto.Subscription.DeliveryConfig.DeliveryRequirement;
import java.util.concurrent.ExecutionException;
public class CreateSubscriptionExample {
public static void main(String... args) throws Exception {
// TODO(developer): Replace these variables before running the sample.
String cloudRegion = "your-cloud-region";
char zoneId = 'b';
String topicId = "your-topic-id";
String subscriptionId = "your-subscription-id";
long projectNumber = Long.parseLong("123456789");
// True if using a regional location. False if using a zonal location.
// https://cloud.google.com/pubsub/lite/docs/topics
boolean regional = false;
createSubscriptionExample(
cloudRegion, zoneId, projectNumber, topicId, subscriptionId, regional);
}
public static void createSubscriptionExample(
String cloudRegion,
char zoneId,
long projectNumber,
String topicId,
String subscriptionId,
boolean regional)
throws Exception {
CloudRegionOrZone location;
if (regional) {
location = CloudRegionOrZone.of(CloudRegion.of(cloudRegion));
} else {
location = CloudRegionOrZone.of(CloudZone.of(CloudRegion.of(cloudRegion), zoneId));
}
TopicPath topicPath =
TopicPath.newBuilder()
.setProject(ProjectNumber.of(projectNumber))
.setLocation(location)
.setName(TopicName.of(topicId))
.build();
SubscriptionPath subscriptionPath =
SubscriptionPath.newBuilder()
.setLocation(location)
.setProject(ProjectNumber.of(projectNumber))
.setName(SubscriptionName.of(subscriptionId))
.build();
Subscription subscription =
Subscription.newBuilder()
.setDeliveryConfig(
// Possible values for DeliveryRequirement:
// - `DELIVER_IMMEDIATELY`
// - `DELIVER_AFTER_STORED`
// You may choose whether to wait for a published message to be successfully written
// to storage before the server delivers it to subscribers. `DELIVER_IMMEDIATELY` is
// suitable for applications that need higher throughput.
DeliveryConfig.newBuilder()
.setDeliveryRequirement(DeliveryRequirement.DELIVER_IMMEDIATELY))
.setName(subscriptionPath.toString())
.setTopic(topicPath.toString())
.build();
AdminClientSettings adminClientSettings =
AdminClientSettings.newBuilder().setRegion(CloudRegion.of(cloudRegion)).build();
try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
Subscription response = adminClient.createSubscription(subscription).get();
System.out.println(response.getAllFields() + " created successfully.");
} catch (ExecutionException e) {
try {
throw e.getCause();
} catch (AlreadyExistsException alreadyExists) {
System.out.println("This subscription already exists.");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
}
Python
Pub/Sub Lite에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
from google.api_core.exceptions import AlreadyExists
from google.cloud.pubsublite import AdminClient, Subscription
from google.cloud.pubsublite.types import (
CloudRegion,
CloudZone,
SubscriptionPath,
TopicPath,
)
# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"
# regional = True
if regional:
location = CloudRegion(cloud_region)
else:
location = CloudZone(CloudRegion(cloud_region), zone_id)
topic_path = TopicPath(project_number, location, topic_id)
subscription_path = SubscriptionPath(project_number, location, subscription_id)
subscription = Subscription(
name=str(subscription_path),
topic=str(topic_path),
delivery_config=Subscription.DeliveryConfig(
# Possible values for delivery_requirement:
# - `DELIVER_IMMEDIATELY`
# - `DELIVER_AFTER_STORED`
# You may choose whether to wait for a published message to be successfully written
# to storage before the server delivers it to subscribers. `DELIVER_IMMEDIATELY` is
# suitable for applications that need higher throughput.
delivery_requirement=Subscription.DeliveryConfig.DeliveryRequirement.DELIVER_IMMEDIATELY,
),
)
client = AdminClient(cloud_region)
try:
response = client.create_subscription(subscription)
print(f"{response.name} created successfully.")
except AlreadyExists:
print(f"{subscription_path} already exists.")
다음 단계
다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.