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

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

刪除 Amazon SNS 主題和訂閱

刪除主題時,會以非同步方式刪除其相關聯的訂閱。雖然客戶仍然可以存取這些訂閱,但即使您使用相同名稱重新建立主題,訂閱也不再與主題相關聯。如果發佈者嘗試發佈訊息到已刪除的主題,發佈者將會收到錯誤訊息,指出主題不存在。同樣地,只要嘗試訂閱已刪除的主題也會產生錯誤訊息。您無法刪除正在進行確認的訂閱。Amazon SNS 會在 48 小時後自動刪除未確認的訂閱。

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

刪除 Amazon SNS 主題或訂閱可確保有效率的資源管理、防止不必要的使用,並保持 Amazon SNS 主控台井然有序。此步驟有助於避免閒置資源的潛在成本,並移除不再需要的主題或訂閱,以簡化管理。

使用 刪除主題 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 程式碼範例儲存庫中設定和執行。

import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // 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(ctx context.Context, topicArn string) error { _, err := actor.SnsClient.DeleteTopic(ctx, &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 詳細資訊,請參閱 適用於 Go 的 AWS SDK API 參考中的 DeleteTopic

Java
SDK for Java 2.x
注意

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
SDK for 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
SDK for Kotlin
注意

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.") } }
PHP
SDK for 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
SDK for Python (Boto3)
注意

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 SDK for Python (Boto3) API 參考中的 DeleteTopic

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 詳細資訊,請參閱《適用於 Kotlin 的AWS SDK API 參考》中的 DeleteTopic

Swift
SDK for Swift
注意

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

let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) _ = try await snsClient.deleteTopic( input: DeleteTopicInput(topicArn: arn) )
  • 如需 API 詳細資訊,請參閱 AWS SDK for Swift API 參考中的 DeleteTopic