Chapter 36. AWS Simple Queue Service Component


Available as of Camel version 2.6

The sqs component supports sending and receiving messages to Amazon’s SQS service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon SQS. More information are available at Amazon SQS.

36.1. URI Format

aws-sqs://queueNameOrArn[?options]

The queue will be created if they don’t already exists.
You can append query options to the URI in the following format, ?options=value&option2=value&…​

36.2. URI Options

The AWS Simple Queue Service component supports 5 options, which are listed below.

NameDescriptionDefaultType

configuration (advanced)

The AWS SQS default configuration

 

SqsConfiguration

accessKey (common)

Amazon AWS Access Key

 

String

secretKey (common)

Amazon AWS Secret Key

 

String

region (common)

Specify the queue region which could be used with queueOwnerAWSAccountId to build the service URL.

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS Simple Queue Service endpoint is configured using URI syntax:

aws-sqs:queueNameOrArn

with the following path and query parameters:

36.2.1. Path Parameters (1 parameters):

NameDescriptionDefaultType

queueNameOrArn

Required Queue name or ARN

 

String

36.2.2. Query Parameters (49 parameters):

NameDescriptionDefaultType

amazonAWSHost (common)

The hostname of the Amazon AWS cloud.

amazonaws.com

String

amazonSQSClient (common)

To use the AmazonSQS as client

 

AmazonSQS

headerFilterStrategy (common)

To use a custom HeaderFilterStrategy to map headers to/from Camel.

 

HeaderFilterStrategy

queueOwnerAWSAccountId (common)

Specify the queue owner aws account id when you need to connect the queue with different account owner.

 

String

region (common)

Specify the queue region which could be used with queueOwnerAWSAccountId to build the service URL.

 

String

useIAMCredentials (common)

Set whether the SQS client should expect to load credentials on an EC2 instance or to expect static credentials to be passed in.

false

boolean

attributeNames (consumer)

A list of attribute names to receive when consuming. Multiple names can be separated by comma.

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

concurrentConsumers (consumer)

Allows you to use multiple threads to poll the sqs queue to increase throughput

1

int

defaultVisibilityTimeout (consumer)

The default visibility timeout (in seconds)

 

Integer

deleteAfterRead (consumer)

Delete message from SQS after it has been read

true

boolean

deleteIfFiltered (consumer)

Whether or not to send the DeleteMessage to the SQS queue if an exchange fails to get through a filter. If 'false' and exchange does not make it through a Camel filter upstream in the route, then don’t send DeleteMessage.

true

boolean

extendMessageVisibility (consumer)

If enabled then a scheduled background task will keep extending the message visibility on SQS. This is needed if it takes a long time to process the message. If set to true defaultVisibilityTimeout must be set. See details at Amazon docs.

false

boolean

maxMessagesPerPoll (consumer)

Gets the maximum number of messages as a limit to poll at each polling. Is default unlimited, but use 0 or negative number to disable it as unlimited.

 

int

messageAttributeNames (consumer)

A list of message attribute names to receive when consuming. Multiple names can be separated by comma.

 

String

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

visibilityTimeout (consumer)

The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved by a ReceiveMessage request to set in the com.amazonaws.services.sqs.model.SetQueueAttributesRequest. This only make sense if its different from defaultVisibilityTimeout. It changes the queue visibility timeout attribute permanently.

 

Integer

waitTimeSeconds (consumer)

Duration in seconds (0 to 20) that the ReceiveMessage action call will wait until a message is in the queue to include in the response.

 

Integer

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

 

ExceptionHandler

exchangePattern (consumer)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

pollStrategy (consumer)

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

 

PollingConsumerPoll Strategy

delaySeconds (producer)

Delay sending messages for a number of seconds.

 

Integer

messageDeduplicationId Strategy (producer)

Only for FIFO queues. Strategy for setting the messageDeduplicationId on the message. Can be one of the following options: useExchangeId, useContentBasedDeduplication. For the useContentBasedDeduplication option, no messageDeduplicationId will be set on the message.

useExchangeId

MessageDeduplicationId Strategy

messageGroupIdStrategy (producer)

Only for FIFO queues. Strategy for setting the messageGroupId on the message. Can be one of the following options: useConstant, useExchangeId, usePropertyValue. For the usePropertyValue option, the value of property CamelAwsMessageGroupId will be used.

 

MessageGroupIdStrategy

delayQueue (advanced)

Define if you want to apply delaySeconds option to the queue or on single messages

false

boolean

queueUrl (advanced)

To define the queueUrl explicitly. All other parameters, which would influence the queueUrl, are ignored. This parameter is intended to be used, to connect to a mock implementation of SQS, for testing purposes.

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

 

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

 

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

 

int

delay (scheduler)

Milliseconds before the next poll. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

initialDelay (scheduler)

Milliseconds before the first poll starts. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

1000

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

 

ScheduledExecutor Service

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz2 component

none

ScheduledPollConsumer Scheduler

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz2, Spring based scheduler.

 

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

proxyHost (proxy)

To define a proxy host when instantiating the SQS client

 

String

proxyPort (proxy)

To define a proxy port when instantiating the SQS client

 

Integer

maximumMessageSize (queue)

The maximumMessageSize (in bytes) an SQS message can contain for this queue.

 

Integer

messageRetentionPeriod (queue)

The messageRetentionPeriod (in seconds) a message will be retained by SQS for this queue.

 

Integer

policy (queue)

The policy for this queue

 

String

receiveMessageWaitTime Seconds (queue)

If you do not specify WaitTimeSeconds in the request, the queue attribute ReceiveMessageWaitTimeSeconds is used to determine how long to wait.

 

Integer

redrivePolicy (queue)

Specify the policy that send message to DeadLetter queue. See detail at Amazon docs.

 

String

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

36.3. Spring Boot Auto-Configuration

The component supports 31 options, which are listed below.

NameDescriptionDefaultType

camel.component.aws-sqs.access-key

Amazon AWS Access Key

 

String

camel.component.aws-sqs.configuration.access-key

Amazon AWS Access Key

 

String

camel.component.aws-sqs.configuration.amazon-a-w-s-host

The hostname of the Amazon AWS cloud.

amazonaws.com

String

camel.component.aws-sqs.configuration.amazon-s-q-s-client

To use the AmazonSQS as client

 

AmazonSQS

camel.component.aws-sqs.configuration.attribute-names

A list of attribute names to receive when consuming. Multiple names can be separated by comma.

 

String

camel.component.aws-sqs.configuration.concurrent-consumers

Allows you to use multiple threads to poll the sqs queue to increase throughput

1

Integer

camel.component.aws-sqs.configuration.default-visibility-timeout

The default visibility timeout (in seconds)

 

Integer

camel.component.aws-sqs.configuration.delay-queue

Define if you want to apply delaySeconds option to the queue or on single messages

false

Boolean

camel.component.aws-sqs.configuration.delay-seconds

Delay sending messages for a number of seconds.

 

Integer

camel.component.aws-sqs.configuration.delete-after-read

Delete message from SQS after it has been read

true

Boolean

camel.component.aws-sqs.configuration.delete-if-filtered

Whether or not to send the DeleteMessage to the SQS queue if an exchange fails to get through a filter. If 'false' and exchange does not make it through a Camel filter upstream in the route, then don’t send DeleteMessage.

true

Boolean

camel.component.aws-sqs.configuration.extend-message-visibility

If enabled then a scheduled background task will keep extending the message visibility on SQS. This is needed if it takes a long time to process the message. If set to true defaultVisibilityTimeout must be set. See details at Amazon docs.

false

Boolean

camel.component.aws-sqs.configuration.maximum-message-size

The maximumMessageSize (in bytes) an SQS message can contain for this queue.

 

Integer

camel.component.aws-sqs.configuration.message-attribute-names

A list of message attribute names to receive when consuming. Multiple names can be separated by comma.

 

String

camel.component.aws-sqs.configuration.message-retention-period

The messageRetentionPeriod (in seconds) a message will be retained by SQS for this queue.

 

Integer

camel.component.aws-sqs.configuration.policy

The policy for this queue

 

String

camel.component.aws-sqs.configuration.proxy-host

To define a proxy host when instantiating the SQS client

 

String

camel.component.aws-sqs.configuration.proxy-port

To define a proxy port when instantiating the SQS client

 

Integer

camel.component.aws-sqs.configuration.queue-name

Name of queue. The queue will be created if they don’t already exists.

 

String

camel.component.aws-sqs.configuration.queue-owner-a-w-s-account-id

Specify the queue owner aws account id when you need to connect the queue with different account owner.

 

String

camel.component.aws-sqs.configuration.queue-url

To define the queueUrl explicitly. All other parameters, which would influence the queueUrl, are ignored. This parameter is intended to be used, to connect to a mock implementation of SQS, for testing purposes.

 

String

camel.component.aws-sqs.configuration.receive-message-wait-time-seconds

If you do not specify WaitTimeSeconds in the request, the queue attribute ReceiveMessageWaitTimeSeconds is used to determine how long to wait.

 

Integer

camel.component.aws-sqs.configuration.redrive-policy

Specify the policy that send message to DeadLetter queue. See detail at Amazon docs.

 

String

camel.component.aws-sqs.configuration.region

Specify the queue region which could be used with queueOwnerAWSAccountId to build the service URL.

 

String

camel.component.aws-sqs.configuration.secret-key

Amazon AWS Secret Key

 

String

camel.component.aws-sqs.configuration.visibility-timeout

The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved by a ReceiveMessage request to set in the com.amazonaws.services.sqs.model.SetQueueAttributesRequest. This only make sense if its different from defaultVisibilityTimeout. It changes the queue visibility timeout attribute permanently.

 

Integer

camel.component.aws-sqs.configuration.wait-time-seconds

Duration in seconds (0 to 20) that the ReceiveMessage action call will wait until a message is in the queue to include in the response.

 

Integer

camel.component.aws-sqs.enabled

Enable aws-sqs component

true

Boolean

camel.component.aws-sqs.region

Specify the queue region which could be used with queueOwnerAWSAccountId to build the service URL.

 

String

camel.component.aws-sqs.resolve-property-placeholders

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

Boolean

camel.component.aws-sqs.secret-key

Amazon AWS Secret Key

 

String

Required SQS component options

You have to provide the amazonSQSClient in the Registry or your accessKey and secretKey to access the Amazon’s SQS.

36.4. Batch Consumer

This component implements the Batch Consumer.

This allows you for instance to know how many messages exists in this batch and for instance let the Aggregator aggregate this number of messages.

36.5. Usage

36.5.1. Message headers set by the SQS producer

HeaderTypeDescription

CamelAwsSqsMD5OfBody

String

The MD5 checksum of the Amazon SQS message.

CamelAwsSqsMessageId

String

The Amazon SQS message ID.

CamelAwsSqsDelaySeconds

Integer

Since Camel 2.11, the delay seconds that the Amazon SQS message can be see by others.

36.5.2. Message headers set by the SQS consumer

HeaderTypeDescription

CamelAwsSqsMD5OfBody

String

The MD5 checksum of the Amazon SQS message.

CamelAwsSqsMessageId

String

The Amazon SQS message ID.

CamelAwsSqsReceiptHandle

String

The Amazon SQS message receipt handle.

CamelAwsSqsMessageAttributes

Map<String, String>

The Amazon SQS message attributes.

36.5.3. Advanced AmazonSQS configuration

If your Camel Application is running behind a firewall or if you need to have more control over the AmazonSQS instance configuration, you can create your own instance:

AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");

ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

AmazonSQS client = new AmazonSQSClient(awsCredentials, clientConfiguration);

registry.bind("client", client);

and refer to it in your Camel aws-sqs component configuration:

from("aws-sqs://MyQueue?amazonSQSClient=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");

36.5.4. Creating or updating an SQS Queue

In the SQS Component, when an endpoint is started, a check is executed to obtain information about the existence of the queue or not. You’re able to customize the creation through the QueueAttributeName mapping with the SQSConfiguration option.

from("aws-sqs://MyQueue?amazonSQSClient=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");

In this example if the MyQueue queue is not already created on AWS, it will be created with default parameters from the SQS configuration. If it’s already up on AWS, the SQS configuration options will be used to override the existent AWS configuration.

36.5.5. DelayQueue VS Delay for Single message

From 2.23.0 the component has a new option: delayQueue. When the option is set to true, the SQS Queue will be a DelayQueue with the DelaySeconds option as delay. For more information about DelayQueue you can read the AWS SQS documentation. One important information to take into account is the following:

  • For standard queues, the per-queue delay setting is not retroactive—changing the setting doesn’t affect the delay of messages already in the queue.
  • For FIFO queues, the per-queue delay setting is retroactive—changing the setting affects the delay of messages already in the queue.

as stated in the official documentation. If you want to specify a delay on single messages, you can ignore the delayQueue option, while you can set this option to true, if you need to add a fixed delay to all messages enqueued.

36.5.6. Using AWS IAM credentials with the SQS component

To use AWS IAM credentials, you must first confirm that the EC2 instance on which you are launching the Camel application has an IAM role associated with it and that the appropriate policies are attached.

This feature should only be set to true on remote instances. Additionally, you must also use static credentials locally as IAM is an AWS specific component.

To implement this feature set useIAMCredentials to true.

Note

To toggle this feature on and off based on local and remote environments, you could consider enabling this query parameter with system environment variables. For example, your code could set the useIAMCredentials query parameter to true if a system environment variable named isRemote is set to true.

Although this feature does not eliminate the need for static credentials completely, using IAM credentials on AWS environments does remove the need to refresh on remote environments and is more secure as IAM credentials are refreshed automatically every six hours and are also updated when EC2 security policies are updated.

This is the AWS recommended way to manage credentials and therefore should be used as often as possible.

36.6. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>

where ${camel-version} must be replaced by the actual version of Camel (2.6 or higher).

36.7. JMS-style Selectors

SQS does not allow selectors, but you can effectively achieve this by using the Camel Filter EIP and setting an appropriate visibilityTimeout. When SQS dispatches a message, it will wait up to the visibility timeout before it will try to dispatch the message to a different consumer unless a DeleteMessage is received. By default, Camel will always send the DeleteMessage at the end of the route, unless the route ended in failure. To achieve appropriate filtering and not send the DeleteMessage even on successful completion of the route, use a Filter:

from("aws-sqs://MyQueue?amazonSQSClient=#client&defaultVisibilityTimeout=5000&deleteIfFiltered=false")
.filter("${header.login} == true")
.to("mock:result");

In the above code, if an exchange doesn’t have an appropriate header, it will not make it through the filter AND also not be deleted from the SQS queue. After 5000 miliseconds, the message will become visible to other consumers.

36.8. Delete Single Message

Use deleteMessage operation to delete a single message. You’ll need to set a receipt handle header for the message you want to delete.

from("direct:start")
  .setHeader(SqsConstants.SQS_OPERATION, constant("deleteMessage"))
  .setHeader(SqsConstants.RECEIPT_HANDLE, constant("123456"))
  .to("aws-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)&region=EU_WEST_1");

As result you’ll get an exchange containing a DeleteMessageResult instance, that you can use to check if the message was deleted or not.

36.9. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.