구독에 대한 'DeadLetterPolicy'를 업데이트합니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
C++
이 샘플을 사용해 보기 전에 Pub/Sub 빠른 시작: 클라이언트 라이브러리 사용의 C++ 설정 안내를 따르세요. 자세한 내용은 Pub/Sub C++ API 참고 문서를 확인하세요.
Pub/Sub에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
namespace pubsub_admin = ::google::cloud::pubsub_admin;
namespace pubsub = ::google::cloud::pubsub;
[](pubsub_admin::SubscriptionAdminClient client,
std::string const& project_id, std::string const& subscription_id,
std::string const& dead_letter_topic_id,
int dead_letter_delivery_attempts) {
google::pubsub::v1::UpdateSubscriptionRequest request;
request.mutable_subscription()->set_name(
pubsub::Subscription(project_id, subscription_id).FullName());
request.mutable_subscription()
->mutable_dead_letter_policy()
->set_dead_letter_topic(
pubsub::Topic(project_id, dead_letter_topic_id).FullName());
request.mutable_subscription()
->mutable_dead_letter_policy()
->set_max_delivery_attempts(dead_letter_delivery_attempts);
*request.mutable_update_mask()->add_paths() = "dead_letter_policy";
auto sub = client.UpdateSubscription(request);
if (!sub) throw std::move(sub).status();
std::cout << "The subscription has been updated to: " << sub->DebugString()
<< "\n";
std::cout << "It will forward dead letter messages to: "
<< sub->dead_letter_policy().dead_letter_topic() << "\n";
std::cout << "After " << sub->dead_letter_policy().max_delivery_attempts()
<< " delivery attempts.\n";
}
C#
이 샘플을 사용해 보기 전에 Pub/Sub 빠른 시작: 클라이언트 라이브러리 사용의 C# 설정 안내를 따르세요. 자세한 내용은 Pub/Sub C# API 참고 문서를 확인하세요.
Pub/Sub에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
using Google.Cloud.PubSub.V1;
using Google.Protobuf.WellKnownTypes;
public class UpdateDeadLetterPolicySample
{
public Subscription UpdateDeadLetterPolicy(string projectId, string topicId, string subscriptionId, string deadLetterTopicId)
{
SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
// This is an existing topic that the subscription with dead letter policy is attached to.
TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
// This is an existing subscription with a dead letter policy.
SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
// This is an existing dead letter topic that the subscription with dead letter policy forwards
// dead letter messages to.
var deadLetterTopic = TopicName.FromProjectTopic(projectId, deadLetterTopicId).ToString();
// Construct the subscription with the dead letter policy you expect to have after the update.
// Here, values in the required fields (name, topic) help identify the subscription.
var subscription = new Subscription
{
SubscriptionName = subscriptionName,
TopicAsTopicName = topicName,
DeadLetterPolicy = new DeadLetterPolicy
{
DeadLetterTopic = deadLetterTopic,
MaxDeliveryAttempts = 20,
}
};
var request = new UpdateSubscriptionRequest
{
Subscription = subscription,
// Construct a field mask to indicate which field to update in the subscription.
UpdateMask = new FieldMask { Paths = { "dead_letter_policy" } }
};
var updatedSubscription = subscriber.UpdateSubscription(request);
return updatedSubscription;
}
}
Go
이 샘플을 사용해 보기 전에 Pub/Sub 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Go API 참고 문서를 확인하세요.
Pub/Sub에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
import (
"context"
"fmt"
"io"
"cloud.google.com/go/pubsub"
)
// updateDeadLetter updates an existing subscription with a dead letter policy.
func updateDeadLetter(w io.Writer, projectID, subID string, fullyQualifiedDeadLetterTopic string) error {
// projectID := "my-project-id"
// subID := "my-sub"
// fullyQualifiedDeadLetterTopic := "projects/my-project/topics/my-dead-letter-topic"
ctx := context.Background()
client, err := pubsub.NewClient(ctx, projectID)
if err != nil {
return fmt.Errorf("pubsub.NewClient: %w", err)
}
defer client.Close()
updateConfig := pubsub.SubscriptionConfigToUpdate{
DeadLetterPolicy: &pubsub.DeadLetterPolicy{
DeadLetterTopic: fullyQualifiedDeadLetterTopic,
MaxDeliveryAttempts: 20,
},
}
subConfig, err := client.Subscription(subID).Update(ctx, updateConfig)
if err != nil {
return fmt.Errorf("Update: %w", err)
}
fmt.Fprintf(w, "Updated subscription config: %+v\n", subConfig)
return nil
}
Java
이 샘플을 사용해 보기 전에 Pub/Sub 빠른 시작: 클라이언트 라이브러리 사용의 Java 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Java API 참고 문서를 확인하세요.
Pub/Sub에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.protobuf.FieldMask;
import com.google.pubsub.v1.DeadLetterPolicy;
import com.google.pubsub.v1.Subscription;
import com.google.pubsub.v1.SubscriptionName;
import com.google.pubsub.v1.TopicName;
import com.google.pubsub.v1.UpdateSubscriptionRequest;
import java.io.IOException;
public class UpdateDeadLetterPolicyExample {
public static void main(String... args) throws Exception {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
// This is an existing subscription with a dead letter policy.
String subscriptionId = "your-subscription-id";
// This is an existing topic that the subscription with dead letter policy is attached to.
String topicId = "your-topic-id";
// This is an existing dead letter topic that the subscription with dead letter policy forwards
// dead letter messages to.
String deadLetterTopicId = "your-dead-letter-topic-id";
UpdateDeadLetterPolicyExample.updateDeadLetterPolicyExample(
projectId, subscriptionId, topicId, deadLetterTopicId);
}
public static void updateDeadLetterPolicyExample(
String projectId, String subscriptionId, String topicId, String deadLetterTopicId)
throws IOException {
try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
System.out.println(
"Before: " + subscriptionAdminClient.getSubscription(subscriptionName).getAllFields());
TopicName topicName = TopicName.of(projectId, topicId);
TopicName deadLetterTopicName = TopicName.of(projectId, deadLetterTopicId);
// Construct the dead letter policy you expect to have after the update.
DeadLetterPolicy deadLetterPolicy =
DeadLetterPolicy.newBuilder()
.setDeadLetterTopic(deadLetterTopicName.toString())
.setMaxDeliveryAttempts(20)
.build();
// Construct the subscription with the dead letter policy you expect to have
// after the update. Here, values in the required fields (name, topic) help
// identify the subscription.
Subscription subscription =
Subscription.newBuilder()
.setName(subscriptionName.toString())
.setTopic(topicName.toString())
.setDeadLetterPolicy(deadLetterPolicy)
.build();
// Construct a field mask to indicate which field to update in the subscription.
FieldMask updateMask =
FieldMask.newBuilder().addPaths("dead_letter_policy.max_delivery_attempts").build();
UpdateSubscriptionRequest request =
UpdateSubscriptionRequest.newBuilder()
.setSubscription(subscription)
.setUpdateMask(updateMask)
.build();
Subscription response = subscriptionAdminClient.updateSubscription(request);
System.out.println("After: " + response.getAllFields());
System.out.println(
"Max delivery attempts is now "
+ response.getDeadLetterPolicy().getMaxDeliveryAttempts());
}
}
}
Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';
// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function updateDeadLetterPolicy(topicNameOrId, subscriptionNameOrId) {
const metadata = {
deadLetterPolicy: {
deadLetterTopic: pubSubClient.topic(topicNameOrId).name,
maxDeliveryAttempts: 15,
},
};
await pubSubClient
.topic(topicNameOrId)
.subscription(subscriptionNameOrId)
.setMetadata(metadata);
console.log('Max delivery attempts updated successfully.');
}
Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';
// Imports the Google Cloud client library
import {PubSub, SubscriptionMetadata} from '@google-cloud/pubsub';
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function updateDeadLetterPolicy(
topicNameOrId: string,
subscriptionNameOrId: string
) {
const metadata: SubscriptionMetadata = {
deadLetterPolicy: {
deadLetterTopic: pubSubClient.topic(topicNameOrId).name,
maxDeliveryAttempts: 15,
},
};
await pubSubClient
.topic(topicNameOrId)
.subscription(subscriptionNameOrId)
.setMetadata(metadata);
console.log('Max delivery attempts updated successfully.');
}
PHP
이 샘플을 사용해 보기 전에 Pub/Sub 빠른 시작: 클라이언트 라이브러리 사용의 PHP 설정 안내를 따르세요. 자세한 내용은 Pub/Sub PHP API 참고 문서를 확인하세요.
Pub/Sub에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
use Google\Cloud\PubSub\PubSubClient;
/**
* Set the dead letter policy on an existing subscription.
*
* @param string $projectId The Google project ID.
* @param string $topicName The Pub/Sub topic name.
* @param string $deadLetterTopicName The Pub/Sub topic to use for dead letter policy.
*/
function dead_letter_update_subscription(
string $projectId,
string $topicName,
string $subscriptionName,
string $deadLetterTopicName
): void {
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
$topic = $pubsub->topic($topicName);
$deadLetterTopic = $pubsub->topic($deadLetterTopicName);
$subscription = $topic->subscription($subscriptionName);
$subscription->update([
'deadLetterPolicy' => [
'deadLetterTopic' => $deadLetterTopic
]
]);
printf(
'Subscription %s updated with dead letter topic %s' . PHP_EOL,
$subscription->name(),
$deadLetterTopic->name()
);
}
Python
이 샘플을 사용해 보기 전에 Pub/Sub 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Python API 참고 문서를 확인하세요.
Pub/Sub에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
from google.cloud import pubsub_v1
from google.cloud.pubsub_v1.types import DeadLetterPolicy, FieldMask
# TODO(developer)
# project_id = "your-project-id"
# TODO(developer): This is an existing topic that the subscription
# with dead letter policy is attached to.
# topic_id = "your-topic-id"
# TODO(developer): This is an existing subscription with a dead letter policy.
# subscription_id = "your-subscription-id"
# TODO(developer): This is an existing dead letter topic that the subscription
# with dead letter policy will forward dead letter messages to.
# dead_letter_topic_id = "your-dead-letter-topic-id"
# TODO(developer): This is the maximum number of delivery attempts allowed
# for a message before it gets delivered to a dead letter topic.
# max_delivery_attempts = 5
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
topic_path = publisher.topic_path(project_id, topic_id)
subscription_path = subscriber.subscription_path(project_id, subscription_id)
dead_letter_topic_path = publisher.topic_path(project_id, dead_letter_topic_id)
subscription_before_update = subscriber.get_subscription(
request={"subscription": subscription_path}
)
print(f"Before the update: {subscription_before_update}.")
# Indicates which fields in the provided subscription to update.
update_mask = FieldMask(paths=["dead_letter_policy"])
# Construct a dead letter policy you expect to have after the update.
dead_letter_policy = DeadLetterPolicy(
dead_letter_topic=dead_letter_topic_path,
max_delivery_attempts=max_delivery_attempts,
)
# Construct the subscription with the dead letter policy you expect to have
# after the update. Here, values in the required fields (name, topic) help
# identify the subscription.
subscription = pubsub_v1.types.Subscription(
name=subscription_path,
topic=topic_path,
dead_letter_policy=dead_letter_policy,
)
with subscriber:
subscription_after_update = subscriber.update_subscription(
request={"subscription": subscription, "update_mask": update_mask}
)
print(f"After the update: {subscription_after_update}.")
Ruby
이 샘플을 사용해 보기 전에 Pub/Sub 빠른 시작: 클라이언트 라이브러리 사용의 Ruby 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Ruby API 참고 문서를 확인하세요.
Pub/Sub에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
# subscription_id = "your-subscription-id"
# role = "roles/pubsub.publisher"
# service_account_email = "serviceAccount:account_name@project_name.iam.gserviceaccount.com"
pubsub = Google::Cloud::Pubsub.new
subscription = pubsub.subscription subscription_id
subscription.dead_letter_max_delivery_attempts = 20
puts "Max delivery attempts is now #{subscription.dead_letter_max_delivery_attempts}."
다음 단계
다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.