AWS Simple Notification System (SNS)
Since Camel 3.1
Only producer is supported
The AWS2 SNS component allows messages to be sent to an Amazon Simple Notification Topic. The implementation of the Amazon API is provided by the AWS SDK.
Prerequisites
You must have a valid Amazon Web Services developer account, and be signed up to use Amazon SNS. More information is available at Amazon SNS.
URI Format
aws2-sns://topicNameOrArn[?options]
The topic will be created if they don’t already exist.
You can append query options to the URI in the following format:
?options=value&option2=value&…
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The AWS Simple Notification System (SNS) component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Whether the endpoint creates the topic when it starts, if no topic with this name exists in the region. A name that ends with .fifo creates a FIFO topic. If false and the topic does not exist, the publish fails. | false | boolean | |
Whether the producer publishes a batch of messages instead of one. The body must then be a List of the PublishBatchRequestEntry of the AWS SDK, at most 10, and the producer replaces it with the PublishBatchResponse. The subject, messageStructure and message group and deduplication options and the headers are not used for a batch. | false | boolean | |
The configuration that the endpoints of this component start from. Each endpoint gets a copy of it, and the options of the endpoint replace its values. | Sns2Configuration | ||
The ID, alias or ARN of the AWS KMS key that encrypts the topic, for example alias/aws/sns for the AWS managed key of Amazon SNS. It is used only when the endpoint creates the topic and serverSideEncryptionEnabled is true, and it is required then. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
How the producer sets the message deduplication ID for a FIFO topic: useExchangeId uses the ID of the exchange, and useContentBasedDeduplication sets none, so that Amazon SNS deduplicates by the content of the message, which the topic must enable. A FIFO topic that the endpoint creates with useContentBasedDeduplication has content-based deduplication enabled. Enum values:
| useExchangeId | String | |
How the producer sets the message group ID for a FIFO topic: useConstant puts all messages in one group, useExchangeId uses the ID of the exchange, and usePropertyValue the exchange property CamelAwsSnsMessageGroupId. Amazon SNS requires a message group ID for a FIFO topic, so set this option for one. It is not used for a standard topic. Enum values:
| String | ||
Set to json to send a different message for each protocol: the body is then a JSON object with a default key and a key per protocol, such as email or sqs. The CamelAwsSnsMessageStructure header replaces this option. It is not used when batchEnabled is true. | String | ||
Whether to send the requests to the URI of the uriEndpointOverride option instead of the endpoint of the region. It has no effect when uriEndpointOverride is not set. | false | boolean | |
The access policy of the topic, a JSON document that the endpoint sets on the topic when it starts, also on a topic that exists already. It is loaded from the classpath by default; use the prefix file: or http: to load it from another location. | String | ||
The ARN of the Amazon SQS queue that the endpoint subscribes to the topic when it starts, if subscribeSNStoSQS is true. The access policy of the queue must allow the topic to send messages to it. | String | ||
The AWS region of Amazon SNS, as a region ID such as eu-west-1, which is the value of Region.EU_WEST_1.id(). If not set, the default region provider chain of the AWS SDK is used. When the topic is given as an ARN, its region replaces the region of the component, and this option on the endpoint replaces both. Enum values:
| String | ||
Whether the topic that the endpoint creates, see autoCreateTopic, is encrypted with the AWS KMS key of the kmsMasterKeyId option. It does not change a topic that exists already. | false | boolean | |
The subject of the message, which Amazon SNS uses as the Subject line of the email for email subscriptions. The CamelAwsSnsSubject header replaces this option. The producer cuts a subject longer than 100 characters, and does not use it when batchEnabled is true. | String | ||
Whether the endpoint subscribes the Amazon SQS queue of the queueArn option to the topic when it starts. The queueArn option is required then. | false | boolean | |
The URI of the endpoint to use instead of the endpoint of the region, for example http://localhost:4566 for a local emulator. It is used only when overrideEndpoint is true. | String | ||
Autowired To use a custom software.amazon.awssdk.services.sns.SnsClient, which is autowired when the registry has a single one. When this option is set, the credentials, region, proxy, endpoint override and trustAllCertificates options are not used. The endpoint does not close a client that is set or autowired. | SnsClient | ||
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
Used for enabling or disabling all consumer based health checks from this component. | true | boolean | |
Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | boolean | |
The host name of the proxy that the HTTP client of Amazon SNS connects through. The proxy is used only when the proxyPort option is set too. | String | ||
The port of the proxy that the HTTP client of Amazon SNS connects through. The proxy is used only when the proxyHost option is set too. | Integer | ||
The protocol that the HTTP client of Amazon SNS uses to connect to the proxy. It is used only when the proxyHost and proxyPort options are set. Enum values:
| HTTPS | Protocol | |
The access key ID of the AWS credentials, used together with the secretKey option. The endpoint requires it, unless amazonSNSClient is set or useDefaultCredentialsProvider, useProfileCredentialsProvider or useSessionCredentials is true. | String | ||
The name of the profile in the AWS shared credentials and config files, used when useProfileCredentialsProvider is true. If not set, the AWS SDK uses its default profile, which the AWS_PROFILE environment variable can change. | String | ||
The secret access key of the AWS credentials, used together with the accessKey option. The endpoint requires it, unless amazonSNSClient is set or useDefaultCredentialsProvider, useProfileCredentialsProvider or useSessionCredentials is true. | String | ||
The session token of temporary AWS credentials, for example of an assumed IAM role. It is used only when useSessionCredentials is true, together with the accessKey and secretKey options. When it is not set, the accessKey and secretKey options are used without a session token. | String | ||
Whether the HTTP client of Amazon SNS trusts every TLS certificate without checking it. It applies to any endpoint, not only to an overridden one, so use it only for testing, for example against a local emulator. | false | boolean | |
Whether to load the credentials with the default credentials provider chain of the AWS SDK, which looks in system properties, environment variables, the shared credentials and config files, and the container or instance role. It takes precedence over the other credentials options. | false | boolean | |
Whether to load the credentials from a profile of the AWS shared credentials and config files, the one of the profileCredentialsName option. It is not used when useDefaultCredentialsProvider is true, and it takes precedence over the session and static credentials. | false | boolean | |
Whether to use temporary credentials made of the accessKey, secretKey and sessionToken options, for example those of an assumed IAM role. It is not used when useDefaultCredentialsProvider or useProfileCredentialsProvider is true. | false | boolean |
Endpoint Options
The AWS Simple Notification System (SNS) endpoint is configured using URI syntax:
aws2-sns:topicNameOrArn
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The name of the topic, or its ARN in the form arn:aws:sns:region:account:name. For a name, the endpoint looks up the ARN of the topic in the region when it starts, and creates the topic if autoCreateTopic is true and none exists. A topic whose name ends with .fifo is a FIFO topic. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Whether the endpoint creates the topic when it starts, if no topic with this name exists in the region. A name that ends with .fifo creates a FIFO topic. If false and the topic does not exist, the publish fails. | false | boolean | |
Whether the producer publishes a batch of messages instead of one. The body must then be a List of the PublishBatchRequestEntry of the AWS SDK, at most 10, and the producer replaces it with the PublishBatchResponse. The subject, messageStructure and message group and deduplication options and the headers are not used for a batch. | false | boolean | |
To use a custom HeaderFilterStrategy to choose which headers the producer sends as message attributes. The default skips the headers that start with Camel or camel, and breadcrumbId. A header is sent only if its value is a String, Number, Date, byte[], ByteBuffer or List. | HeaderFilterStrategy | ||
The ID, alias or ARN of the AWS KMS key that encrypts the topic, for example alias/aws/sns for the AWS managed key of Amazon SNS. It is used only when the endpoint creates the topic and serverSideEncryptionEnabled is true, and it is required then. | String | ||
How the producer sets the message deduplication ID for a FIFO topic: useExchangeId uses the ID of the exchange, and useContentBasedDeduplication sets none, so that Amazon SNS deduplicates by the content of the message, which the topic must enable. A FIFO topic that the endpoint creates with useContentBasedDeduplication has content-based deduplication enabled. Enum values:
| useExchangeId | String | |
How the producer sets the message group ID for a FIFO topic: useConstant puts all messages in one group, useExchangeId uses the ID of the exchange, and usePropertyValue the exchange property CamelAwsSnsMessageGroupId. Amazon SNS requires a message group ID for a FIFO topic, so set this option for one. It is not used for a standard topic. Enum values:
| String | ||
Set to json to send a different message for each protocol: the body is then a JSON object with a default key and a key per protocol, such as email or sqs. The CamelAwsSnsMessageStructure header replaces this option. It is not used when batchEnabled is true. | String | ||
Whether to send the requests to the URI of the uriEndpointOverride option instead of the endpoint of the region. It has no effect when uriEndpointOverride is not set. | false | boolean | |
The access policy of the topic, a JSON document that the endpoint sets on the topic when it starts, also on a topic that exists already. It is loaded from the classpath by default; use the prefix file: or http: to load it from another location. | String | ||
The ARN of the Amazon SQS queue that the endpoint subscribes to the topic when it starts, if subscribeSNStoSQS is true. The access policy of the queue must allow the topic to send messages to it. | String | ||
The AWS region of Amazon SNS, as a region ID such as eu-west-1, which is the value of Region.EU_WEST_1.id(). If not set, the default region provider chain of the AWS SDK is used. When the topic is given as an ARN, its region replaces the region of the component, and this option on the endpoint replaces both. Enum values:
| String | ||
Whether the topic that the endpoint creates, see autoCreateTopic, is encrypted with the AWS KMS key of the kmsMasterKeyId option. It does not change a topic that exists already. | false | boolean | |
The subject of the message, which Amazon SNS uses as the Subject line of the email for email subscriptions. The CamelAwsSnsSubject header replaces this option. The producer cuts a subject longer than 100 characters, and does not use it when batchEnabled is true. | String | ||
Whether the endpoint subscribes the Amazon SQS queue of the queueArn option to the topic when it starts. The queueArn option is required then. | false | boolean | |
The URI of the endpoint to use instead of the endpoint of the region, for example http://localhost:4566 for a local emulator. It is used only when overrideEndpoint is true. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Autowired To use a custom software.amazon.awssdk.services.sns.SnsClient, which is autowired when the registry has a single one. When this option is set, the credentials, region, proxy, endpoint override and trustAllCertificates options are not used. The endpoint does not close a client that is set or autowired. | SnsClient | ||
The host name of the proxy that the HTTP client of Amazon SNS connects through. The proxy is used only when the proxyPort option is set too. | String | ||
The port of the proxy that the HTTP client of Amazon SNS connects through. The proxy is used only when the proxyHost option is set too. | Integer | ||
The protocol that the HTTP client of Amazon SNS uses to connect to the proxy. It is used only when the proxyHost and proxyPort options are set. Enum values:
| HTTPS | Protocol | |
The access key ID of the AWS credentials, used together with the secretKey option. The endpoint requires it, unless amazonSNSClient is set or useDefaultCredentialsProvider, useProfileCredentialsProvider or useSessionCredentials is true. | String | ||
The name of the profile in the AWS shared credentials and config files, used when useProfileCredentialsProvider is true. If not set, the AWS SDK uses its default profile, which the AWS_PROFILE environment variable can change. | String | ||
The secret access key of the AWS credentials, used together with the accessKey option. The endpoint requires it, unless amazonSNSClient is set or useDefaultCredentialsProvider, useProfileCredentialsProvider or useSessionCredentials is true. | String | ||
The session token of temporary AWS credentials, for example of an assumed IAM role. It is used only when useSessionCredentials is true, together with the accessKey and secretKey options. When it is not set, the accessKey and secretKey options are used without a session token. | String | ||
Whether the HTTP client of Amazon SNS trusts every TLS certificate without checking it. It applies to any endpoint, not only to an overridden one, so use it only for testing, for example against a local emulator. | false | boolean | |
Whether to load the credentials with the default credentials provider chain of the AWS SDK, which looks in system properties, environment variables, the shared credentials and config files, and the container or instance role. It takes precedence over the other credentials options. | false | boolean | |
Whether to load the credentials from a profile of the AWS shared credentials and config files, the one of the profileCredentialsName option. It is not used when useDefaultCredentialsProvider is true, and it takes precedence over the session and static credentials. | false | boolean | |
Whether to use temporary credentials made of the accessKey, secretKey and sessionToken options, for example those of an assumed IAM role. It is not used when useDefaultCredentialsProvider or useProfileCredentialsProvider is true. | false | boolean |
Message Headers
The AWS Simple Notification System (SNS) component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelAwsSnsMessageId (producer) Constant: | The ID that Amazon SNS assigned to the published message. The producer sets it after a publish, but not when batchEnabled is true. | String | |
| Constant: | The subject of the message, which Amazon SNS uses as the Subject line of the email for email subscriptions. It replaces the subject option. The producer cuts a subject longer than 100 characters, and does not use it when batchEnabled is true. | String | |
CamelAwsSnsMessageStructure (producer) Constant: | Set to json to send a different message for each protocol, with the body a JSON object with a default key and a key per protocol. It replaces the messageStructure option, and is not used when batchEnabled is true. | String | |
CamelAwsSnsSequenceNumber (producer) Constant: | The sequence number that Amazon SNS assigned to the message in a FIFO topic. The producer sets it after a publish, with no value for a standard topic, and not when batchEnabled is true. | String | |
CamelAwsSnsFailedMessageCount (producer) Constant: | The number of entries of the batch that Amazon SNS did not publish, which the producer sets when batchEnabled is true. The PublishBatchResponse in the body lists them with the reason. | Integer | |
CamelAwsSnsSuccessfulMessageCount (producer) Constant: | The number of entries of the batch that Amazon SNS published, which the producer sets when batchEnabled is true. The PublishBatchResponse in the body lists them with their message ID. | Integer |
Message Body
The message body at each side of the AWS Simple Notification System (SNS) component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Producer input |
| The message to publish, as text: bytes, a stream or a file are read as text, and a Map or a POJO is sent as its toString(): marshal it first. With messageStructure=json, a JSON object with a message per protocol; with batchEnabled=true, a List of the PublishBatchRequestEntry of the AWS SDK.
|
Producer output |
| Unchanged after a publish, with the id of the message in a header. With batchEnabled=true, the PublishBatchResponse of the AWS SDK.
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Required SNS component options
You have to provide the amazonSNSClient in the Registry or your accessKey and secretKey to access the Amazon’s SNS.
Static credentials, Default Credential Provider and Profile Credentials Provider
You have the possibility of avoiding the usage of explicit static credentials by specifying the useDefaultCredentialsProvider option and set it to true.
The order of evaluation for Default Credentials Provider is the following:
-
Java system properties -
aws.accessKeyIdandaws.secretKey. -
Environment variables -
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY. -
Web Identity Token from AWS STS.
-
The shared credentials and config files.
-
Amazon ECS container credentials - loaded from the Amazon ECS if the environment variable
AWS_CONTAINER_CREDENTIALS_RELATIVE_URIis set. -
Amazon EC2 Instance profile credentials.
You have also the possibility of using Profile Credentials Provider, by specifying the useProfileCredentialsProvider option to true and profileCredentialsName to the profile name.
Only one of static, default and profile credentials could be used at the same time.
For more information about this you can look at AWS credentials documentation
Usage
Advanced AmazonSNS configuration
If you need more control over the SnsClient instance configuration you can create your own instance and refer to it from the URI:
-
Java
-
XML
-
YAML
from("direct:start")
.to("aws2-sns://MyTopic?amazonSNSClient=#client"); <route>
<from uri="direct:start"/>
<to uri="aws2-sns://MyTopic?amazonSNSClient=#client"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: aws2-sns://MyTopic
parameters:
amazonSNSClient: "#client" The #client refers to a AmazonSNS in the Registry.
Create a subscription between an AWS SNS Topic and an AWS SQS Queue
You can create a subscription of an SQS Queue to an SNS Topic in this way:
-
Java
-
XML
-
YAML
from("direct:start")
.to("aws2-sns://test-camel-sns1?amazonSNSClient=#amazonSNSClient&subscribeSNStoSQS=true&queueArn=arn:aws:sqs:eu-central-1:123456789012:test_camel"); <route>
<from uri="direct:start"/>
<to uri="aws2-sns://test-camel-sns1?amazonSNSClient=#amazonSNSClient&subscribeSNStoSQS=true&queueArn=arn:aws:sqs:eu-central-1:123456789012:test_camel"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: aws2-sns://test-camel-sns1
parameters:
amazonSNSClient: "#amazonSNSClient"
subscribeSNStoSQS: true
queueArn: "arn:aws:sqs:eu-central-1:123456789012:test_camel" The #amazonSNSClient refers to a SnsClient in the Registry. By specifying subscribeSNStoSQS to true and a queueArn of an existing SQS Queue, you’ll be able to subscribe your SQS Queue to your SNS Topic.
At this point, you can consume messages coming from SNS Topic through your SQS Queue
-
Java
-
XML
-
YAML
from("aws2-sqs://test-camel?amazonSQSClient=#amazonSQSClient&delay=50&maxMessagesPerPoll=5")
.to("..."); <route>
<from uri="aws2-sqs://test-camel?amazonSQSClient=#amazonSQSClient&delay=50&maxMessagesPerPoll=5"/>
<to uri="..."/>
</route> - route:
from:
uri: aws2-sqs://test-camel
parameters:
amazonSQSClient: "#amazonSQSClient"
delay: 50
maxMessagesPerPoll: 5
steps:
- to:
uri: "..." Topic Auto-creation
With the option autoCreateTopic users are able to avoid the auto-creation of an SNS Topic in case it doesn’t exist. The default for this option is false. If set to false, any operation on a non-existent topic in AWS won’t be successful and an error will be returned.
SNS FIFO
SNS FIFO are supported. While creating the SQS queue, you will subscribe to the SNS topic there is an important point to remember, you’ll need to make possible for the SNS Topic to send the message to the SQS Queue.
This is clear with an example.
Suppose you created an SNS FIFO Topic called Order.fifo and an SQS Queue called QueueSub.fifo.
In the access Policy of the QueueSub.fifo you should submit something like this
{
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Sid": "__owner_statement",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::780560123482:root"
},
"Action": "SQS:*",
"Resource": "arn:aws:sqs:eu-west-1:780560123482:QueueSub.fifo"
},
{
"Effect": "Allow",
"Principal": {
"Service": "sns.amazonaws.com"
},
"Action": "SQS:SendMessage",
"Resource": "arn:aws:sqs:eu-west-1:780560123482:QueueSub.fifo",
"Condition": {
"ArnLike": {
"aws:SourceArn": "arn:aws:sns:eu-west-1:780410022472:Order.fifo"
}
}
}
]
} This is a critical step to make the subscription work correctly.
SNS Fifo Topic Message group ID Strategy and message Deduplication ID Strategy
When sending something to the FIFO topic, you’ll need to always set up a message group ID strategy.
If the content-based message deduplication has been enabled on the SNS Fifo topic, where won’t be the need of setting a message deduplication id strategy, otherwise you’ll have to set it.
Message Subject Length Limitation
AWS SNS has a maximum subject length of 100 characters. If you send a message with a subject longer than 100 characters (for example, when using CloudEvents with long subjects), the subject will be automatically truncated to 100 characters.
This behavior ensures compatibility with AWS SNS constraints while allowing seamless integration with systems like CloudEvents that do not impose such restrictions.
Examples
Producer Examples
Sending to a topic
-
Java
-
XML
-
YAML
from("direct:start")
.to("aws2-sns://camel-topic?subject=The+subject+message&autoCreateTopic=true"); <route>
<from uri="direct:start"/>
<to uri="aws2-sns://camel-topic?subject=The+subject+message&autoCreateTopic=true"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: aws2-sns://camel-topic
parameters:
subject: "The+subject+message"
autoCreateTopic: true Sending batch to a topic
PublishBatchRequestEntry objects programmaticallyfrom("direct:start")
.process(exchange -> {
List<PublishBatchRequestEntry> pubList = List.of(
PublishBatchRequestEntry.builder().id("message1").message("This is message 1").build(),
PublishBatchRequestEntry.builder().id("message2").message("This is message 2").build(),
PublishBatchRequestEntry.builder().id("message3").message("This is message 3").build()
);
exchange.getIn().setBody(pubList);
})
.to("aws2-sns://camel-topic?subject=The+subject+message&autoCreateTopic=true&batchEnabled=true"); Dependencies
Maven users will need to add the following dependency to their pom.xml.
pom.xml
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-sns</artifactId>
<version>${camel-version}</version>
</dependency> where ${camel-version} must be replaced by the actual version of Camel.