Utilisation DeleteTopic avec un AWS SDK ou un outil de ligne de commande - Amazon Simple Notification Service

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Utilisation DeleteTopic avec un AWS SDK ou un outil de ligne de commande

Les exemples de code suivants montrent comment utiliserDeleteTopic.

Les exemples d’actions sont des extraits de code de programmes de plus grande envergure et doivent être exécutés en contexte. Vous pouvez voir cette action en contexte dans l’exemple de code suivant :

.NET
AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Supprimez une rubrique à l'aide de son ARN de rubrique.

/// <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; }
  • Pour plus de détails sur l'API, reportez-vous DeleteTopicà la section Référence des AWS SDK for .NET API.

C++
Kit SDK pour C++
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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(); }
  • Pour plus de détails sur l'API, reportez-vous DeleteTopicà la section Référence des AWS SDK for C++ API.

CLI
AWS CLI

Pour supprimer une rubrique SNS

L'exemple delete-topic suivant supprime la rubrique SNS spécifiée.

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

Cette commande ne produit aucun résultat.

  • Pour plus de détails sur l'API, reportez-vous DeleteTopicà la section Référence des AWS CLI commandes.

Go
Kit SDK for Go V2
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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 }
  • Pour plus de détails sur l'API, reportez-vous DeleteTopicà la section Référence des AWS SDK for Go API.

Java
Kit SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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); } } }
  • Pour plus de détails sur l'API, reportez-vous DeleteTopicà la section Référence des AWS SDK for Java 2.x API.

JavaScript
SDK pour JavaScript (v3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Créez le client dans un module séparé et exportez-le.

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({});

Importez le kit SDK et les modules client et appelez l’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
Kits SDK pour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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.") } }
  • Pour plus de détails sur l'API, consultez DeleteTopicla section AWS SDK pour la référence de l'API Kotlin.

PHP
Kit SDK pour PHP
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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()); }
  • Pour plus de détails sur l'API, reportez-vous DeleteTopicà la section Référence des AWS SDK for PHP API.

Python
Kit SDK pour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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
  • Pour plus de détails sur l'API, consultez DeleteTopicle AWS manuel de référence de l'API SDK for Python (Boto3).

SAP ABAP
Kit SDK pour SAP ABAP
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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.
  • Pour plus de détails sur l'API, consultez DeleteTopicla section de référence du AWS SDK pour l'API SAP ABAP.

Pour obtenir la liste complète des guides de développement du AWS SDK et des exemples de code, consultezUtilisation d'Amazon SNS avec un kit SDK AWS. Cette rubrique comprend également des informations sur le démarrage et sur les versions précédentes du kit SDK.