Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.
Creare un argomento Amazon SNS
Un argomento Amazon SNS è un punto di accesso logico che funge da canale di comunicazione. Un argomento consente di raggruppare più endpoint (ad esempio Amazon SQS AWS Lambda, HTTP/S o un indirizzo e-mail).
Per trasmettere i messaggi di un sistema producer (ad esempio un sito Web di E-Commerce) e che opera con più servizi diversi dai quali tali messaggi sono richiesti (ad esempio i sistemi di pagamento ed evasione degli ordini), puoi creare un argomento per il sistema producer.
La prima attività di Amazon SNS, nonché la più comune, è la creazione di un argomento. Questa pagina mostra come utilizzare il AWS Management Console, il e il AWS SDK for Java AWS SDK for .NET per creare un argomento.
Durante la creazione, è possibile scegliere un tipo di argomento (standard o FIFO) e assegnare un nome all'argomento. Una volta creato un argomento, non è possibile modificare il tipo o il nome dell'argomento. Tutte le altre opzioni di configurazione sono facoltative durante la creazione dell'argomento ed è possibile modificarle in un secondo momento.
Non aggiungere informazioni personali di identificazione (PII) o altre informazioni riservate o sensibili nei nomi dei argomenti. I nomi degli argomenti sono accessibili ad altri Amazon Web Services, inclusi CloudWatch i log. I nomi dei argomenti non sono destinati ad essere utilizzati per dati privati o sensibili.
Per creare un argomento utilizzando il AWS Management Console
Accedi alla console Amazon SNS.
-
Esegui una di queste operazioni:
-
Nella pagina Topics (Argomenti), seleziona Create new topic (Crea nuovo argomento).
-
Nella pagina Create topic (Crea argomento), nella sezione Details (Dettagli), eseguire queste operazioni:
-
Per Type (Tipo), scegli un tipo di argomento (standard o FIFO).
-
Immetti un nome per l'argomento. Per un Argomento FIFO, aggiungere .fifo alla fine del nome.
-
(Facoltativo) Compilare il Display name (Nome visualizzato) per l'argomento.
Quando si effettua la sottoscrizione di un endpoint e-mail, il numero combinato di caratteri del nome dell'argomento Amazon SNS mostrato e dell'indirizzo e-mail da cui viene eseguito l'invio (ad esempio, no-reply@sns.amazonaws.com) non deve essere superiore a 320 caratteri UTF-8. È possibile utilizzare uno strumento di codifica di terze parti per verificare la lunghezza dell'indirizzo da cui eseguire l'invio prima di configurare un nome da mostrare per l'argomento Amazon SNS.
-
(Facoltativo) Per un argomento FIFO, puoi scegliere Deduplicazione dei messaggi basata sul contenuto per abilitare la deduplicazione predefinita dei messaggi. Per ulteriori informazioni, consulta Deduplicazione dei messaggi per argomenti FIFO.
-
(Facoltativo) Espandere la sezione Encryption (Crittografia) e procedere come segue. Per ulteriori informazioni, consulta Crittografia a riposo.
-
Scegliere Enable encryption (Abilita crittografia).
-
Specificate la AWS KMS chiave. Per ulteriori informazioni, consulta Termini chiave.
Per ciascun tipo di KMS vengono visualizzati i valori Description (Descrizione), Account e KMS ARN (ARN KMS).
Se non sei il proprietario della KMS, oppure se effettui l'accesso con un account che non dispone delle autorizzazioni kms:ListAliases
e kms:DescribeKey
, non puoi visualizzare le informazioni sulla KMS sulla console Amazon SNS.
Chiedi al proprietario della KMS di concederti queste autorizzazioni. Per esempi e ulteriori informazioni consulta AWS KMS Autorizzazioni API: e Documentazione su operazioni e risorse nella AWS Key Management Service Guida per sviluppatori.
-
Il KMS AWS gestito per Amazon SNS (predefinito) alias/aws/sns è selezionato per impostazione predefinita.
Ricorda quanto segue:
-
La prima volta che usi AWS Management Console per specificare il KMS AWS gestito per Amazon SNS per un argomento AWS KMS , crea AWS il KMS gestito per Amazon SNS.
-
In alternativa, la prima volta che utilizzi l'Publish
azione su un argomento con SSE abilitato, AWS KMS crea il KMS AWS gestito per Amazon SNS.
-
Per utilizzare un KMS personalizzato dal tuo AWS account, scegli il campo chiave KMS, quindi scegli il KMS personalizzato dall'elenco.
Per istruzioni sulla creazione di KMS personalizzate, consulta Creazione di chiavi nella Guida per gli sviluppatori di AWS Key Management Service
-
Per utilizzare un ARN KMS personalizzato dal AWS tuo account o da AWS un altro account, inseriscilo nel campo della chiave KMS.
-
(Facoltativo) Per impostazione predefinita, solo il proprietario dell'argomento può pubblicare o sottoscrivere l'argomento. Per configurare autorizzazioni di accesso aggiuntive, espandi la sezione Access policy (Policy di accesso) . Per ulteriori informazioni, consulta Identity and Access Management in Amazon SNS e Esempi di casi per il controllo degli accessi Amazon SNS.
Quando crei un argomento utilizzando la console, la policy predefinita utilizza la chiave di condizione aws:SourceOwner
. Questa chiave è analoga a aws:SourceAccount
.
-
(Facoltativo) Per configurare il modo in cui Amazon SNS riprova a consegnare i messaggi non recapitati, espandere la sezione Delivery retry policy (HTTP/S) (Policy nuovi tentativi di consegna [HTTP/S]). Per ulteriori informazioni, consulta Tentativi di consegna dei messaggi di Amazon SNS.
-
(Facoltativo) Per configurare il modo in cui Amazon SNS registra la consegna dei messaggi CloudWatch, espandi la sezione Registrazione dello stato di consegna. Per ulteriori informazioni, consulta Stato di consegna dei messaggi Amazon SNS.
-
(facoltativo) Per aggiungere tag di metadati all'argomento, espandere la sezione Tags (Tag), immettere una Key (Chiave) e un Value (Valore) (opzionale) e scegliere Add tag (Aggiungi tag). Per ulteriori informazioni, consulta Assegnazione di tag all'argomento Amazon SNS.
-
Scegliere Create topic (Crea argomento).
L'argomento viene creato e la MyTopic
pagina viene visualizzata.
Il nome dell'argomento, l'ARN, (opzionale) il nome visualizzato e l'ID AWS account del proprietario dell'argomento vengono visualizzati nella sezione Dettagli.
-
Copiare l'ARN dell'argomento negli appunti, ad esempio:
arn:aws:sns:us-east-2:123456789012:MyTopic
Per creare un argomento utilizzando un SDK AWS
Per utilizzare un AWS SDK, devi configurarlo con le tue credenziali. Per ulteriori informazioni, consulta File di configurazione e credenziali condivisi nella Guida di riferimento per SDK AWS e strumenti.
I seguenti esempi di codice mostrano come utilizzare. CreateTopic
- .NET
-
- AWS SDK for .NET
-
Crea un argomento con un nome di specifico.
using System;
using System.Threading.Tasks;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
/// <summary>
/// This example shows how to use Amazon Simple Notification Service
/// (Amazon SNS) to add a new Amazon SNS topic.
/// </summary>
public class CreateSNSTopic
{
public static async Task Main()
{
string topicName = "ExampleSNSTopic";
IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();
var topicArn = await CreateSNSTopicAsync(client, topicName);
Console.WriteLine($"New topic ARN: {topicArn}");
}
/// <summary>
/// Creates a new SNS topic using the supplied topic name.
/// </summary>
/// <param name="client">The initialized SNS client object used to
/// create the new topic.</param>
/// <param name="topicName">A string representing the topic name.</param>
/// <returns>The Amazon Resource Name (ARN) of the created topic.</returns>
public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName)
{
var request = new CreateTopicRequest
{
Name = topicName,
};
var response = await client.CreateTopicAsync(request);
return response.TopicArn;
}
}
Crea un nuovo argomento con un nome e attributi FIFO e di deduplicazione specifici.
/// <summary>
/// Create a new topic with a name and specific FIFO and de-duplication attributes.
/// </summary>
/// <param name="topicName">The name for the topic.</param>
/// <param name="useFifoTopic">True to use a FIFO topic.</param>
/// <param name="useContentBasedDeduplication">True to use content-based de-duplication.</param>
/// <returns>The ARN of the new topic.</returns>
public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication)
{
var createTopicRequest = new CreateTopicRequest()
{
Name = topicName,
};
if (useFifoTopic)
{
// Update the name if it is not correct for a FIFO topic.
if (!topicName.EndsWith(".fifo"))
{
createTopicRequest.Name = topicName + ".fifo";
}
// Add the attributes from the method parameters.
createTopicRequest.Attributes = new Dictionary<string, string>
{
{ "FifoTopic", "true" }
};
if (useContentBasedDeduplication)
{
createTopicRequest.Attributes.Add("ContentBasedDeduplication", "true");
}
}
var createResponse = await _amazonSNSClient.CreateTopicAsync(createTopicRequest);
return createResponse.TopicArn;
}
- C++
-
- SDK per C++
-
//! Create an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
\param topicName: An Amazon SNS topic name.
\param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool AwsDoc::SNS::createTopic(const Aws::String &topicName,
Aws::String &topicARNResult,
const Aws::Client::ClientConfiguration &clientConfiguration) {
Aws::SNS::SNSClient snsClient(clientConfiguration);
Aws::SNS::Model::CreateTopicRequest request;
request.SetName(topicName);
const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request);
if (outcome.IsSuccess()) {
topicARNResult = outcome.GetResult().GetTopicArn();
std::cout << "Successfully created an Amazon SNS topic " << topicName
<< " with topic ARN '" << topicARNResult
<< "'." << std::endl;
}
else {
std::cerr << "Error creating topic " << topicName << ":" <<
outcome.GetError().GetMessage() << std::endl;
topicARNResult.clear();
}
return outcome.IsSuccess();
}
- CLI
-
- AWS CLI
-
Creazione di un argomento SNS
Nell'esempio create-topic
seguente viene creato un argomento SNS denominato my-topic
.
aws sns create-topic \
--name my-topic
Output:
{
"ResponseMetadata": {
"RequestId": "1469e8d7-1642-564e-b85d-a19b4b341f83"
},
"TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic"
}
Per ulteriori informazioni, consulta Using the AWS Command Line Interface with Amazon SQS e Amazon SNS nella Command Line Interface AWS User Guide.
- Go
-
- SDK per Go V2
-
// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type SnsActions struct {
SnsClient *sns.Client
}
// CreateTopic creates an Amazon SNS topic with the specified name. You can optionally
// specify that the topic is created as a FIFO topic and whether it uses content-based
// deduplication instead of ID-based deduplication.
func (actor SnsActions) CreateTopic(topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) {
var topicArn string
topicAttributes := map[string]string{}
if isFifoTopic {
topicAttributes["FifoTopic"] = "true"
}
if contentBasedDeduplication {
topicAttributes["ContentBasedDeduplication"] = "true"
}
topic, err := actor.SnsClient.CreateTopic(context.TODO(), &sns.CreateTopicInput{
Name: aws.String(topicName),
Attributes: topicAttributes,
})
if err != nil {
log.Printf("Couldn't create topic %v. Here's why: %v\n", topicName, err)
} else {
topicArn = *topic.TopicArn
}
return topicArn, err
}
- Java
-
- SDK per Java 2.x
-
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
import software.amazon.awssdk.services.sns.model.CreateTopicResponse;
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 CreateTopic {
public static void main(String[] args) {
final String usage = """
Usage: <topicName>
Where:
topicName - The name of the topic to create (for example, mytopic).
""";
if (args.length != 1) {
System.out.println(usage);
System.exit(1);
}
String topicName = args[0];
System.out.println("Creating a topic with name: " + topicName);
SnsClient snsClient = SnsClient.builder()
.region(Region.US_EAST_1)
.build();
String arnVal = createSNSTopic(snsClient, topicName);
System.out.println("The topic ARN is" + arnVal);
snsClient.close();
}
public static String createSNSTopic(SnsClient snsClient, String topicName) {
CreateTopicResponse result;
try {
CreateTopicRequest request = CreateTopicRequest.builder()
.name(topicName)
.build();
result = snsClient.createTopic(request);
return result.topicArn();
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
}
}
- JavaScript
-
- SDK per JavaScript (v3)
-
Creare il client in un modulo separato ed esportarlo.
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({});
Importare l'SDK e i moduli client e chiamare l'API.
import { CreateTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";
/**
* @param {string} topicName - The name of the topic to create.
*/
export const createTopic = async (topicName = "TOPIC_NAME") => {
const response = await snsClient.send(
new CreateTopicCommand({ Name: topicName }),
);
console.log(response);
// {
// '$metadata': {
// httpStatusCode: 200,
// requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e',
// extendedRequestId: undefined,
// cfId: undefined,
// attempts: 1,
// totalRetryDelay: 0
// },
// TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME'
// }
return response;
};
- Kotlin
-
- SDK per Kotlin
-
suspend fun createSNSTopic(topicName: String): String {
val request = CreateTopicRequest {
name = topicName
}
SnsClient { region = "us-east-1" }.use { snsClient ->
val result = snsClient.createTopic(request)
return result.topicArn.toString()
}
}
- PHP
-
- SDK per PHP
-
require 'vendor/autoload.php';
use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
/**
* Create a Simple Notification Service topics in your AWS account at the requested region.
*
* 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'
]);
$topicname = 'myTopic';
try {
$result = $SnSclient->createTopic([
'Name' => $topicname,
]);
var_dump($result);
} catch (AwsException $e) {
// output error message if fails
error_log($e->getMessage());
}
- Python
-
- SDK per Python (Boto3)
-
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
def create_topic(self, name):
"""
Creates a notification topic.
:param name: The name of the topic to create.
:return: The newly created topic.
"""
try:
topic = self.sns_resource.create_topic(Name=name)
logger.info("Created topic %s with ARN %s.", name, topic.arn)
except ClientError:
logger.exception("Couldn't create topic %s.", name)
raise
else:
return topic
- Ruby
-
- SDK per Ruby
-
# This class demonstrates how to create an Amazon Simple Notification Service (SNS) topic.
class SNSTopicCreator
# Initializes an SNS client.
#
# Utilizes the default AWS configuration for region and credentials.
def initialize
@sns_client = Aws::SNS::Client.new
end
# Attempts to create an SNS topic with the specified name.
#
# @param topic_name [String] The name of the SNS topic to create.
# @return [Boolean] true if the topic was successfully created, false otherwise.
def create_topic(topic_name)
@sns_client.create_topic(name: topic_name)
puts "The topic '#{topic_name}' was successfully created."
true
rescue Aws::SNS::Errors::ServiceError => e
# Handles SNS service errors gracefully.
puts "Error while creating the topic named '#{topic_name}': #{e.message}"
false
end
end
# Example usage:
if $PROGRAM_NAME == __FILE__
topic_name = "YourTopicName" # Replace with your topic name
sns_topic_creator = SNSTopicCreator.new
puts "Creating the topic '#{topic_name}'..."
unless sns_topic_creator.create_topic(topic_name)
puts "The topic was not created. Stopping program."
exit 1
end
end
- Rust
-
- SDK per Rust
-
async fn make_topic(client: &Client, topic_name: &str) -> Result<(), Error> {
let resp = client.create_topic().name(topic_name).send().await?;
println!(
"Created topic with ARN: {}",
resp.topic_arn().unwrap_or_default()
);
Ok(())
}
- SAP ABAP
-
- SDK per SAP ABAP
-
TRY.
oo_result = lo_sns->createtopic( iv_name = iv_topic_name ). " oo_result is returned for testing purposes. "
MESSAGE 'SNS topic created' TYPE 'I'.
CATCH /aws1/cx_snstopiclimitexcdex.
MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'.
ENDTRY.