PublishÚselo con un AWS SDK o CLI - Ejemplos de código de AWS SDK

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

PublishÚselo con un AWS SDK o CLI

En los siguientes ejemplos de código, se muestra cómo utilizar Publish.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en los siguientes ejemplos de código:

.NET
AWS SDK for .NET
nota

Hay más en marcha GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Publique un mensaje en un tema.

using System; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example publishes a message to an Amazon Simple Notification /// Service (Amazon SNS) topic. /// </summary> public class PublishToSNSTopic { public static async Task Main() { string topicArn = "arn:aws:sns:us-east-2:000000000000:ExampleSNSTopic"; string messageText = "This is an example message to publish to the ExampleSNSTopic."; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); await PublishToTopicAsync(client, topicArn, messageText); } /// <summary> /// Publishes a message to an Amazon SNS topic. /// </summary> /// <param name="client">The initialized client object used to publish /// to the Amazon SNS topic.</param> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="messageText">The text of the message.</param> public static async Task PublishToTopicAsync( IAmazonSimpleNotificationService client, string topicArn, string messageText) { var request = new PublishRequest { TopicArn = topicArn, Message = messageText, }; var response = await client.PublishAsync(request); Console.WriteLine($"Successfully published message ID: {response.MessageId}"); } }

Publique un mensaje en un tema con opciones de grupo, duplicación y atributo.

/// <summary> /// Publish messages using user settings. /// </summary> /// <returns>Async task.</returns> public static async Task PublishMessages() { Console.WriteLine("Now we can publish messages."); var keepSendingMessages = true; string? deduplicationId = null; string? toneAttribute = null; while (keepSendingMessages) { Console.WriteLine(); var message = GetUserResponse("Enter a message to publish.", "This is a sample message"); if (_useFifoTopic) { Console.WriteLine("Because you are using a FIFO topic, you must set a message group ID." + "\r\nAll messages within the same group will be received in the order " + "they were published."); Console.WriteLine(); var messageGroupId = GetUserResponse("Enter a message group ID for this message:", "1"); if (!_useContentBasedDeduplication) { Console.WriteLine("Because you are not using content-based deduplication, " + "you must enter a deduplication ID."); Console.WriteLine("Enter a deduplication ID for this message."); deduplicationId = GetUserResponse("Enter a deduplication ID for this message.", "1"); } if (GetYesNoResponse("Add an attribute to this message?")) { Console.WriteLine("Enter a number for an attribute."); for (int i = 0; i < _tones.Length; i++) { Console.WriteLine($"\t{i + 1}. {_tones[i]}"); } var selection = GetUserResponse("", "1"); int.TryParse(selection, out var selectionNumber); if (selectionNumber > 0 && selectionNumber < _tones.Length) { toneAttribute = _tones[selectionNumber - 1]; } } var messageID = await SnsWrapper.PublishToTopicWithAttribute( _topicArn, message, "tone", toneAttribute, deduplicationId, messageGroupId); Console.WriteLine($"Message published with id {messageID}."); } keepSendingMessages = GetYesNoResponse("Send another message?", false); } }

Aplica las selecciones del usuario a la acción de publicación.

/// <summary> /// Publish a message to a topic with an attribute and optional deduplication and group IDs. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="message">The message to publish.</param> /// <param name="attributeName">The optional attribute for the message.</param> /// <param name="attributeValue">The optional attribute value for the message.</param> /// <param name="deduplicationId">The optional deduplication ID for the message.</param> /// <param name="groupId">The optional group ID for the message.</param> /// <returns>The ID of the message published.</returns> public async Task<string> PublishToTopicWithAttribute( string topicArn, string message, string? attributeName = null, string? attributeValue = null, string? deduplicationId = null, string? groupId = null) { var publishRequest = new PublishRequest() { TopicArn = topicArn, Message = message, MessageDeduplicationId = deduplicationId, MessageGroupId = groupId }; if (attributeValue != null) { // Add the string attribute if it exists. publishRequest.MessageAttributes = new Dictionary<string, MessageAttributeValue> { { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} } }; } var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest); return publishResponse.MessageId; }
  • Para API obtener más información, consulte Publicar en AWS SDK for .NET APIreferencia.

C++
SDKpara C++
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

//! Send a message to an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param message: The message to publish. \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::publishToTopic(const Aws::String &message, const Aws::String &topicARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::PublishRequest request; request.SetMessage(message); request.SetTopicArn(topicARN); const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Message published successfully with id '" << outcome.GetResult().GetMessageId() << "'." << std::endl; } else { std::cerr << "Error while publishing message " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }

Publica un mensaje con un atributo.

static const Aws::String TONE_ATTRIBUTE("tone"); static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious", "sincere"}; Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::PublishRequest request; request.SetTopicArn(topicARN); Aws::String message = askQuestion("Enter a message text to publish. "); request.SetMessage(message); if (filteringMessages && askYesNoQuestion( "Add an attribute to this message? (y/n) ")) { for (size_t i = 0; i < TONES.size(); ++i) { std::cout << " " << (i + 1) << ". " << TONES[i] << std::endl; } int selection = askQuestionForIntRange( "Enter a number for an attribute. ", 1, static_cast<int>(TONES.size())); Aws::SNS::Model::MessageAttributeValue messageAttributeValue; messageAttributeValue.SetDataType("String"); messageAttributeValue.SetStringValue(TONES[selection - 1]); request.AddMessageAttributes(TONE_ATTRIBUTE, messageAttributeValue); } Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Your message was successfully published." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::Publish. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; }
  • Para API obtener más información, consulte Publicar en AWS SDK for C++ APIreferencia.

CLI
AWS CLI

Ejemplo 1: Para publicar un mensaje en un tema

El siguiente publish ejemplo publica el mensaje especificado en el SNS tema especificado. El mensaje proviene de un archivo de texto que le permite incluir saltos de línea.

aws sns publish \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \ --message file://message.txt

Contenidos de message.txt:

Hello World Second Line

Salida:

{ "MessageId": "123a45b6-7890-12c3-45d6-111122223333" }

Ejemplo 2: publicar un SMS mensaje en un número de teléfono

En el siguiente ejemplo de publish, se publica el mensaje Hello world! en el número de teléfono +1-555-555-0100.

aws sns publish \ --message "Hello world!" \ --phone-number +1-555-555-0100

Salida:

{ "MessageId": "123a45b6-7890-12c3-45d6-333322221111" }
  • Para API obtener más información, consulte Publish in AWS CLI Command Reference.

Go
SDKpara Go V2
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // Publish publishes a message to an Amazon SNS topic. The message is then sent to all // subscribers. When the topic is a FIFO topic, the message must also contain a group ID // and, when ID-based deduplication is used, a deduplication ID. An optional key-value // filter attribute can be specified so that the message can be filtered according to // a filter policy. func (actor SnsActions) Publish(topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error { publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)} if groupId != "" { publishInput.MessageGroupId = aws.String(groupId) } if dedupId != "" { publishInput.MessageDeduplicationId = aws.String(dedupId) } if filterKey != "" && filterValue != "" { publishInput.MessageAttributes = map[string]types.MessageAttributeValue{ filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)}, } } _, err := actor.SnsClient.Publish(context.TODO(), &publishInput) if err != nil { log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err) } return err }
  • Para API obtener más información, consulte Publicar en AWS SDK for Go APIreferencia.

Java
SDKpara Java 2.x
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; 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 PublishTopic { public static void main(String[] args) { final String usage = """ Usage: <message> <topicArn> Where: message - The message text to send. topicArn - The ARN of the topic to publish. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String topicArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTopic(snsClient, message, topicArn); snsClient.close(); } public static void pubTopic(SnsClient snsClient, String message, String topicArn) { try { PublishRequest request = PublishRequest.builder() .message(message) .topicArn(topicArn) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para API obtener más información, consulte Publicar en AWS SDK for Java 2.x APIreferencia.

JavaScript
SDKpara JavaScript (v3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurarlo y ejecutarlo en el Repositorio de ejemplos de código de AWS.

Cree el cliente en un módulo separado y expórtelo.

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

Importe los módulos SDK y del cliente y llame alAPI.

import { PublishCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object * if you are using the `json` `MessageStructure`. * @param {string} topicArn - The ARN of the topic to which you would like to publish. */ export const publish = async ( message = "Hello from SNS!", topicArn = "TOPIC_ARN", ) => { const response = await snsClient.send( new PublishCommand({ Message: message, TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };

Publique un mensaje en un tema con opciones de grupo, duplicación y atributo.

async publishMessages() { const message = await this.prompter.input({ message: MESSAGES.publishMessagePrompt, }); let groupId, deduplicationId, choices; if (this.isFifo) { await this.logger.log(MESSAGES.groupIdNotice); groupId = await this.prompter.input({ message: MESSAGES.groupIdPrompt, }); if (this.autoDedup === false) { await this.logger.log(MESSAGES.deduplicationIdNotice); deduplicationId = await this.prompter.input({ message: MESSAGES.deduplicationIdPrompt, }); } choices = await this.prompter.checkbox({ message: MESSAGES.messageAttributesPrompt, choices: toneChoices, }); } await this.snsClient.send( new PublishCommand({ TopicArn: this.topicArn, Message: message, ...(groupId ? { MessageGroupId: groupId, } : {}), ...(deduplicationId ? { MessageDeduplicationId: deduplicationId, } : {}), ...(choices ? { MessageAttributes: { tone: { DataType: "String.Array", StringValue: JSON.stringify(choices), }, }, } : {}), }), ); const publishAnother = await this.prompter.confirm({ message: MESSAGES.publishAnother, }); if (publishAnother) { await this.publishMessages(); } }
Kotlin
SDKpara Kotlin
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

suspend fun pubTopic( topicArnVal: String, messageVal: String, ) { val request = PublishRequest { message = messageVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println("${result.messageId} message sent.") } }
  • Para API obtener más información, consulta Publicar en AWS SDK como APIreferencia sobre Kotlin.

PHP
SDK para PHP
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Sends a message to an Amazon SNS topic. * * 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' ]); $message = 'This message is sent from a Amazon SNS code sample.'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->publish([ 'Message' => $message, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
PowerShell
Herramientas para PowerShell

Ejemplo 1: En este ejemplo se muestra la publicación de un mensaje con una sola línea MessageAttribute declarada.

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}

Ejemplo 2: En este ejemplo se muestra la publicación de un mensaje con varios MessageAttributes declarados de antemano.

$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue $cityAttributeValue.DataType = "String" $cityAttributeValue.StringValue = "AnyCity" $populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue $populationAttributeValue.DataType = "Number" $populationAttributeValue.StringValue = "1250800" $messageAttributes = New-Object System.Collections.Hashtable $messageAttributes.Add("City", $cityAttributeValue) $messageAttributes.Add("Population", $populationAttributeValue) Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
  • Para API obtener más información, consulte Publish in AWS Tools for PowerShell Cmdlet Reference.

Python
SDKpara Python (Boto3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Publique un mensaje con atributos para que una suscripción pueda filtrar en función de los atributos.

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 publish_message(topic, message, attributes): """ Publishes a message, with attributes, to a topic. Subscriptions can be filtered based on message attributes so that a subscription receives messages only when specified attributes are present. :param topic: The topic to publish to. :param message: The message to publish. :param attributes: The key-value attributes to attach to the message. Values must be either `str` or `bytes`. :return: The ID of the message. """ try: att_dict = {} for key, value in attributes.items(): if isinstance(value, str): att_dict[key] = {"DataType": "String", "StringValue": value} elif isinstance(value, bytes): att_dict[key] = {"DataType": "Binary", "BinaryValue": value} response = topic.publish(Message=message, MessageAttributes=att_dict) message_id = response["MessageId"] logger.info( "Published message with attributes %s to topic %s.", attributes, topic.arn, ) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id

Publique un mensaje que toma diferentes formas en función del protocolo del suscriptor.

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 publish_multi_message( topic, subject, default_message, sms_message, email_message ): """ Publishes a multi-format message to a topic. A multi-format message takes different forms based on the protocol of the subscriber. For example, an SMS subscriber might receive a short version of the message while an email subscriber could receive a longer version. :param topic: The topic to publish to. :param subject: The subject of the message. :param default_message: The default version of the message. This version is sent to subscribers that have protocols that are not otherwise specified in the structured message. :param sms_message: The version of the message sent to SMS subscribers. :param email_message: The version of the message sent to email subscribers. :return: The ID of the message. """ try: message = { "default": default_message, "sms": sms_message, "email": email_message, } response = topic.publish( Message=json.dumps(message), Subject=subject, MessageStructure="json" ) message_id = response["MessageId"] logger.info("Published multi-format message to topic %s.", topic.arn) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id
  • Para API obtener más información, consulte Publish in AWS SDKfor Python (Boto3) Reference. API

Ruby
SDKpara Ruby
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

# Service class for sending messages using Amazon Simple Notification Service (SNS) class SnsMessageSender # Initializes the SnsMessageSender with an SNS client # # @param sns_client [Aws::SNS::Client] The SNS client def initialize(sns_client) @sns_client = sns_client @logger = Logger.new($stdout) end # Sends a message to a specified SNS topic # # @param topic_arn [String] The ARN of the SNS topic # @param message [String] The message to send # @return [Boolean] true if message was successfully sent, false otherwise def send_message(topic_arn, message) @sns_client.publish(topic_arn: topic_arn, message: message) @logger.info("Message sent successfully to #{topic_arn}.") true rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error while sending the message: #{e.message}") false end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_arn = "SNS_TOPIC_ARN" # Should be replaced with a real topic ARN message = "MESSAGE" # Should be replaced with the actual message content sns_client = Aws::SNS::Client.new message_sender = SnsMessageSender.new(sns_client) @logger.info("Sending message.") unless message_sender.send_message(topic_arn, message) @logger.error("Message sending failed. Stopping program.") exit 1 end end
Rust
SDKpara Rust
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

async fn subscribe_and_publish( client: &Client, topic_arn: &str, email_address: &str, ) -> Result<(), Error> { println!("Receiving on topic with ARN: `{}`", topic_arn); let rsp = client .subscribe() .topic_arn(topic_arn) .protocol("email") .endpoint(email_address) .send() .await?; println!("Added a subscription: {:?}", rsp); let rsp = client .publish() .topic_arn(topic_arn) .message("hello sns!") .send() .await?; println!("Published message: {:?}", rsp); Ok(()) }
  • Para API obtener más información, consulta Publicar en AWS SDK como APIreferencia a Rust.

SAP ABAP
SDKpara SAP ABAP
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

TRY. oo_result = lo_sns->publish( " oo_result is returned for testing purposes. " iv_topicarn = iv_topic_arn iv_message = iv_message ). MESSAGE 'Message published to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY.
  • Para API obtener más información, consulta Publicar en AWS SDKSAPABAPAPIcomo referencia.