刪除 Amazon SNS 主題和訂閱 - Amazon Simple Notification Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

刪除 Amazon SNS 主題和訂閱

刪除主題時,會以非同步方式刪除其關聯的訂閱。雖然客戶仍然可以存取這些訂閱,但訂閱不再與主題相關聯,即使您使用相同名稱重新建立主題也是如此。

如果訂閱用戶嘗試將訊息發佈到已刪除的主題,發布者將會收到錯誤訊息,指出該主題不存在。同樣地,只要嘗試訂閱已刪除的主題也會產生錯誤訊息。

您無法刪除正在進行確認的訂閱。Amazon SNS 會在 48 小時後自動刪除未確認的訂閱。

若要使用刪除 Amazon SNS 主題或訂閱 AWS Management Console

若要使用刪除主題 AWS Management Console
  1. 登入 Amazon SNS 主控台

  2. 在左側導覽窗格中,選擇 Topics (主題)。

  3. Topics (主題) 頁面上,選取主題,然後選擇 Edit (編輯)。

  4. Delete topic (刪除主題) 對話方塊中輸入 delete me,然後選擇 Delete (刪除)。

    主控台刪除主題。

若要使用刪除訂閱 AWS Management Console
  1. 登入 Amazon SNS 主控台

  2. 在左導覽窗格中,選擇訂閱

  3. 在 [訂閱] 頁面上,選取狀態為 [已確認] 的訂閱,然後選擇 [刪除]。

  4. Delete subscription (刪除訂閱) 對話方塊中,選擇 Delete (刪除)。

    主控台刪除訂閱。

使用 AWS SDK 刪除訂閱和主題

要使用 AWS SDK,您必須使用憑據對其進行配置。如需詳細資訊,請參閱 AWS SDK和工具參考指南中的共享的配置和認證文件

下列程式碼範例會示範如何使用DeleteTopic

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

藉由主題 ARN 刪除該主題。

/// <summary> /// Delete a topic by its topic ARN. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteTopicByArn(string topicArn) { var deleteResponse = await _amazonSNSClient.DeleteTopicAsync( new DeleteTopicRequest() { TopicArn = topicArn }); return deleteResponse.HttpStatusCode == HttpStatusCode.OK; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考DeleteTopic中的。

C++
適用於 C++ 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

//! Delete an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::deleteTopic(const Aws::String &topicARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::DeleteTopicRequest request; request.SetTopicArn(topicARN); const Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request); if (outcome.IsSuccess()) { std::cout << "Successfully deleted the Amazon SNS topic " << topicARN << std::endl; } else { std::cerr << "Error deleting topic " << topicARN << ":" << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for C++ API 參考DeleteTopic中的。

CLI
AWS CLI

刪除 SNS 主題

下列 delete-topic 範例會刪除指定的 SNS 主題。

aws sns delete-topic \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic"

此命令不會產生輸出。

  • 如需 API 詳細資訊,請參閱AWS CLI 命令參考DeleteTopic中的。

Go
SDK for Go V2
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // DeleteTopic delete an Amazon SNS topic. func (actor SnsActions) DeleteTopic(topicArn string) error { _, err := actor.SnsClient.DeleteTopic(context.TODO(), &sns.DeleteTopicInput{ TopicArn: aws.String(topicArn)}) if err != nil { log.Printf("Couldn't delete topic %v. Here's why: %v\n", topicArn, err) } return err }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Go API 參考DeleteTopic中的。

Java
適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; import software.amazon.awssdk.services.sns.model.DeleteTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteTopic { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic to delete. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); System.out.println("Deleting a topic with name: " + topicArn); deleteSNSTopic(snsClient, topicArn); snsClient.close(); } public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() .topicArn(topicArn) .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考DeleteTopic中的。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入 SDK 和用戶端模組,然後呼叫 API。

import { DeleteTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic to delete. */ export const deleteTopic = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new DeleteTopicCommand({ TopicArn: topicArn }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'a10e2886-5a8f-5114-af36-75bd39498332', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } };
Kotlin
適用於 Kotlin 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

suspend fun deleteSNSTopic(topicArnVal: String) { val request = DeleteTopicRequest { topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.deleteTopic(request) println("$topicArnVal was successfully deleted.") } }
  • 有關 API 的詳細信息,請參閱 AWS SDK DeleteTopic中的 Kotlin API 參考。

PHP
適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Deletes an SNS topic and all its subscriptions. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->deleteTopic([ 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for PHP API 參考DeleteTopic中的。

Python
適用於 Python (Boto3) 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def delete_topic(topic): """ Deletes a topic. All subscriptions to the topic are also deleted. """ try: topic.delete() logger.info("Deleted topic %s.", topic.arn) except ClientError: logger.exception("Couldn't delete topic %s.", topic.arn) raise
  • 如需 API 的詳細資訊,請參閱AWS 開發套件DeleteTopic中的 Python (博托 3) API 參考。

SAP ABAP
適用於 SAP ABAP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

TRY. lo_sns->deletetopic( iv_topicarn = iv_topic_arn ). MESSAGE 'SNS topic deleted.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY.
  • 如需 API 詳細資訊,請參閱 AWS SDK DeleteTopic中的 SAP ABAP API 參考資料。