Navigate to <CF_HOME>/cfusion/bin.
Overview
Message queues allow different components of a system to asynchronously communicate between the various components. A message queue provides a buffer that stores messages temporarily and provides endpoints for the components to connect to the queue and send messages. The message can be requests, replies, or error messages.
A message is usually stored in the queue until another service consumes the message and performs some operation.
Amazon Simple Queue Service (SQS) is a queueing service that stores messages that applications or microservices use. Amazon SQS help decouple system components, reduce dependencies, and provides scalability. The reason behind decoupling components is to build the system such that if any single component of the system were to become unresponsive for some reason, the other components would continue to work as usual.
SQS provides an implementation of message queuing software in the cloud. It provides a distributed system for passing messages between computers and application components. Message queues also provide a manner in which systems and components within systems can remain independent and autonomous.
With SQS, the system components use queue buffers to send messages to one another. These queues allow the components to communicate asynchronously, to support concurrency, to remain highly available, and to better handle load and spikes.
Get started
Install awssqs package
Adobe ColdFusion (2021 release) is modularized, if you are only using the ZIP installer. By default, the module for AWS SQS is not installed. The first step is to install the SQS package in ColdFusion.
Note: If you are using the GUI installer, the packages are pre-installed.
The package for SQS is called awssqs.
To install the package awssqs, use the Package Manager page in the ColdFusion Administrator, or follow the steps below:
-
-
Enter the command:
- Windows: cfpm.bat
- Linux: cfpm.sh
-
Enter the command, install awssqs.
Wait for the AWS SQS package to get installed.
For more information, see ColdFusion Package Manager.
Get credentials to access AWS SQS
When you interact with AWS, you specify your AWS security credentials to verify your credentials and check whether you have permission to access the resources that you are requesting.
AWS uses the security credentials to authenticate and authorize your requests.
You must get the AWS Access Key ID and the AWS Secret Access Key. For more information, see Access Keys.
Add cloud service credentials and configuration
In ColdFusion (2021 release), there is a method getCloudService() that gives you a handle to create objects for accessing various cloud services.
The syntax of the service handle is as follows:
service=getCloudService(cloudCred,cloudConfig), where:
- cloudCred: Defines the credentials for the cloud service. It could either be a struct or a string (also known as credential alias).
- cloudConfig: Defines the cloud service configuration details. It could either be a struct or a string (also known as config alias).
After you've acquired the AWS credentials, you must declare these credentials in one of the following ways. Only then you can use these credentials to create a SQS object, after which you can use the object to make calls to the various SQS methods.
ColdFusion Administrator
Set credentials
In the ColdFusion Administrator, click Data & Services > Cloud Credentials.
An alias is a named representation of a cloud service and its configuration details. You can set the config alias through ColdFusion Administrator.
After entering the details, click Add Credential.
Set configuration options
In the ColdFusion Administrator, click Data & Services > Cloud Configuration.
Enter the following details, like configuration Alias, Vendor, and the name of the service.
After adding the configuration options, you may need to add a few more options. You can do so in the next screen. The following are a few options that you may need to add:
- Request config
- Client config
- Proxy settings
- Retry policy
- Retry conditions
For more information, see Cloud configuration options.
Create the object
Once you've created the aliases for SQS credential and configuration options, you can create the object by using the getCloudService API, and include the following in your CFM.
sqsObject= getCloudService("sqsCred", "sqsConf")
Application.cfc
You can specify the SQS credentials and configuration options in Application.cfc. For example,
component { this.name="AWS_STD_Queue"; void function onApplicationStart(){ application.awsCred = { "alias" : "aws_std_queue", "vendorName" : "AWS", "region" : "us-east-1", "secretAccessKey" : "xxxxxxxxxxxxxxxxx", "accessKeyId" : "xxxxxxxxxxxxxxxx" } application.snsConf = { "serviceName" : "SNS" } application.sqsConf ={ "serviceName" : "SQS" } } }
Create the object
sqsObject = getCloudService(application.awsCred, application.sqsConf)
On CFM page
On a CFM page, you can specify the SQS credentials and configuration options in one of the four methods, specified below:
Credential alias and configuration alias
After you've created the aliases for SQS credential and configuration options, you can use these aliases in the getCloudService
handle as shown below:
<cfscript> // define the credential and the configuration aliases in the ColdFusion Admin sqs=getCloudService("awsCred","sqsConf") // code below. ........... </cfscript>
Credential Alias and Struct for configuration options
<cfscript> // Using credential alias and struct for service config sqsConf = { "alias":"sqsConf", "serviceName" : "SQS", "clientOverrideConfig":{ "retryPolicy":{ "numRetries":4 } }, "httpClientConfig":{ "maxConnections":50 } } sqs= getCloudService("sqsCred", sqsConf) // code below ..................... </cfscript>
Configuration alias and struct for credentials
<cfscript> // Using config alias and struct for service credentials // sqs credentials sqsCreds={ "vendorName":"AWS", "alias": "sqsCred", "region":"us-east-2", "accessKeyId": "access key", "secretAccessKey": "secret access" } sqs= getCloudService(sqsCreds, "sqsConf") // code below ..................................... </cfscript>
Structs for both credential and configuration options
<cfscript> // Using Structs for both cloud credential and config sqsCred={ "vendorName":"AWS", "alias": "sqs_cred_alias", "region":"us-east-2", "accessKeyId": "access key", "secretAccessKey": "secret access key" } sqsConf = { "alias":"sqs_conf_alias", "serviceName" : "SQS", "clientOverrideConfig":{ "retryPolicy":{ "numRetries":4 } }, "httpClientConfig":{ "maxConnections":50 } } sqs = getCloudService(sqsCred, sqsConf ) // code below ................................................................... </cfscript>
Admin API
You can also add SQS credentials and configuration options by using the Admin APIs. The methods to add credentials and configuration are available in cloud.cfc.
The examples below demonstrate the usage of the methods addCredential(struct credential) and addServiceConfig(struct config).
Add credentials
<cfscript> // Create an object of administrator component and call the login method adminObj = createObject("component","cfide.adminapi.administrator") adminObj.login("admin") // Create an object of cloud component cloudObj = createObject("component","cfide.adminapi.cloud") // define credentials struct credentialStruct={ "alias" : "CredSQS", "vendorName" : "AWS", "region" : "us-east-2", "secretAccessKey" : "secret access key", "accessKeyId" : "access key" } // add credential credentialStruct try{ cloudObj.addCredential(credentialStruct) writeOutput("Credentials added successfully") } catch(any e){ writeDump(e) } </cfscript>
Add configuration
<cfscript> // Create an object of administrator component and call the login method adminObj = createObject("component","cfide.adminapi.administrator") adminObj.login("admin") // Create an object of cloud component cloudObj = createObject("component","cfide.adminapi.cloud") // define configuration struct configStruct={ "alias":"ConfSQS", "serviceName":"SQS", "clientOverrideConfig":{ "retryPolicy":{ "numRetries":4 } }, "httpClientConfig":{ "maxConnections":50 } } // add config configStruct try{ cloudObj.addServiceConfig(configStruct) writeOutput("Configuration service added successfully") } catch(any e){ writeDump(e) } </cfscript>
CFSetup
You can also set up SQS credential and configuration via the CFSetup configuration utility.
Add cloud credential
- add cloudcredential credentialAlias=sqscred accesskeyid=<access> secretaccesskey=<secret> region=ap-southeast-1 vendorname=AWS
Set credential
- set cloudcredential sqscred secretaccesskey=awssecret
Add cloud configuration
- add cloudconfiguration serviceName=SQS alias=sqsConfig
Set configuration
- set cloudconfiguration conf1 alias=conf2
SQSClient APIs
- SQSQueue createQueue(String queueName);
- SQSQueue createQueue(String queueName, Map queueAttributes);
- String getQueueUrl(String queueName);
- Struct listQueues();
- Struct listQueueTags(String queueUrl);
- Struct purgeQueue(String queueUrl);
- Struct deleteQueue(String queueUrl);
- Struct sendMessage(String queueUrl, Map message);
- Struct receiveMessage(String queueUrl, Map receiveMessageOptions);
- Struct deleteMessage(String queueUrl, Map message);
- Struct tagQueue(String queueUrl, Map tags);
- Struct untagQueue(String queueUrl, Map tags);
- Struct changeMessageVisibility(String queueUrl, Map message);
- Struct setQueueAttributes(String queueUrl, Map queueAttributes);
- Struct getQueueAttributes(String queueUrl, Map queueAttributes);
- Struct changeMessageVisibilityBatch(String queueUrl, List<Map> messages);
- Struct deleteMessageBatch(String queueUrl, List<Map> messages);
- Struct sendMessageBatch(String queueUrl, List<Map> messages);
- Struct listDeadLetterSourceQueues(String queueUrl);
- Struct editTags(String queueUrl, Map tags);
- Struct addPermission(String queueUrl, Map permission);
- Struct removePermission(String queueUrl, String permissionLabel);
- Struct listQueues(String queueNamePrefix);
- String getQueueArn(String queueUrl);
SQSQueue APIs
- public Struct listQueueTags();
- public Struct purge();
- Struct sendMessage(Map message);
- Struct receiveMessage(Map receiveMessageOptions);
- Struct deleteMessage(Map message);
- Struct tag(Map tags);
- Struct untag(Map tags);
- Struct getAttributes(Map attributes);
- Struct setAttributes(Map attributes);
- Struct sendMessageBatch(List<Map> messages);
- Struct deleteMessageBatch(List<Map> messages);
- Struct changeMessageVisibilityBatch(List<Map> messages);
- String getQueueUrl();
- Struct listDeadLetterSourceQueues();
- Struct editTags(Map tags);
- Struct changeMessageVisibility(Map message);
- Struct addPermission(Map permission);
- Struct removePermission(String permissionLabel);
- String getQueueArn();
Create a queue
This function creates a standard or a FIFO queue. While creating a queue, you must ensure the following:
- If you do not specify the attribute FifoQueue, Amazon SQS creates a standard queue.
- If you want to create a FIFO queue, you must use the convention, <QueueName>.fifo.
- While creating a queue, if you do not provide a value for an attribute, the default values of the attribute are used to create the queue.
For more information, see CreateQueue.
Syntax
createQueue(String queueName, Struct queueAttributes)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueName |
Name of the queue. If you want to create a FIFO queue, the queue name must end with the .fifo suffix. Queue names are case-sensitive. |
String |
Yes |
queueAttributes |
Struct of strings containing the following attributes:
Server Side Encryption-related attributes:
FIFO-related attributes:
Note: You cannot change the queue from Standard to FIFO queue and vice-versa. |
Struct |
No |
For more information, see createQueue parameters.
Example
Standard queue
<cfscript> cred={ "credentialAlias" : "alias", "vendorName" : "AWS", "region" : "us-east-2", "secretAccessKey" : "secret access", "accessKeyId" : "access key" } conf={ "serviceName"="SQS" } sqs=getCloudService(cred, conf) queueName="QueueOne" // standard queue myQueue=sqs.createQueue(queueName) try{ myQueue=sqs.createQueue(queueName) writeOutput("Standard queue created") } catch (any e){ writeDump(e) } </cfscript>
Standard queue with attributes
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf) queueName="MyQueue" // Creates a new standard setQueueAttributesMetadata = { "attributes"={ "VisibilityTimeout"="10", "MessageRetentionPeriod"="100", "MaximumMessageSize"="1024", "DelaySeconds"="10", "ReceiveMessageWaitTimeSeconds"="20" } } // standard queue try{ myQueue=sqs.createQueue(queueName,setQueueAttributesMetadata) writeOutput("Queue with attributes created") } catch (any e){ writeDump(e) } </cfscript>
FIFO queue
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf) queueName="MyQueue.fifo" // A FIFO queue name must end with the .fifo suffix // Creates FIFO queue setQueueAttributesMetadata = { "attributes"={ "FifoQueue":"true", // This attribute must be True for a FIFO queue "VisibilityTimeout"="10", "MessageRetentionPeriod"="100", "MaximumMessageSize"="1024", "DelaySeconds"="10", "ReceiveMessageWaitTimeSeconds"="20" } } // FIFO queue try{ myQueue=sqs.createQueue(queueName,setQueueAttributesMetadata) writeOutput("FIFO queue with attributes created") } catch (any e){ writeDump(e) } </cfscript>
Create a queue with SSE
Create a queue and enable Server-Side Encryption (SSE). SSE works with both standard and FIFO queues.
For better encryption, you can use the following:
- Customer Master Key (CMK) ID: Key to encrypt the contents of the messages in SQS. For more information, see Data keys in SQS.
- Customer Data Key Reuse Period: The time, in seconds, for which SQS reuses the data key to encrypt or decrypt messages. The value can be between 60-86400. For more information, see Understanding the Data Key Reuse Period.
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); //Use the sqs service object to create a queue using createQueue(). This method returns a queue object. myQueue = sqs.createQueue("QueueWithSSE"); setQueueAttributesMetadata = { "attributes"={ "KmsMasterKeyId"="arn:aws:kms:us-east-2:xxxxxxxxxxx:key/xxxxxxxxxxxx", "KmsDataKeyReusePeriodSeconds"="120" } }; setQueueAttributesResponse = myQueue.setAttributes(setQueueAttributesMetadata); KmsMasterKeyIdVal = myQueue.getAttributes({ "attributeNames"=["KmsMasterKeyId"] }) val = KmsMasterKeyIdVal["attributes"]; writeoutput(val["KmsMasterKeyId"]); </cfscript>
List all queues
This function lists the number of queues in your AWS account.
For more information, see ListQueues.
Syntax
listQueues(queueNamePrefix)
Parameters
Parameter |
Type |
Required |
---|---|---|
queueNamePrefix |
String |
No |
For more information, see parameters.
In the ListQueues method, the parameters maxResults and nextToken are not supported at present.
Example
<cfscript> // Create a queue in SQS // Get the getCloudService from the credentials and configuration we declared in Application.cfc sqs = getCloudService(application.awsCred, application.sqsConf); // Use the sqs service object to create a queue using createQueue(). // This method returns a queue object. writeoutput("Create queue in AWS</br>"); myQueue = sqs.createQueue("MyQueueWithAttrib") writeoutput("Listing all the queues in AWS<br>") writeDump(sqs.listQueues().queueUrls) writeOutput("The number of queues in the region is:") queueCount= ArrayLen(sqs.listQueues().queueUrls) writeOutput(queueCount) </cfscript>
Get URL of a queue
Retrieve the URL of an Amazon SQS queue.
Syntax
getQueueUrl(queueName)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueName |
The name of the queue whose URL you want to retrieve. |
String |
Yes |
For more information, see request parameters.
Example
<cfscript> sqs=getCloudService(application.awsCred, application.sqsConf) qURL=sqs.GetQueueUrl("BatchQueue") writeDump(qURL) </cfscript>
Get ARN of a queue
Retrieve the Amazon Resource Names (ARNs) of an SQS queue.
Syntax
getQueueArn(String queueUrl)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue. |
String |
Yes |
Example
<cfscript> sqs=getCloudService(application.awsCred, application.sqsConf) stdQueueObj = sqs.createQueue("stdQueueARN"); queueARN = stdQueueObj.getQueueArn(); writeoutput(queueARN) </cfscript>
Tag a queue
This function adds tags, for example, cost allocation, to a specified standard or a FIFO queue. While creating tags, you must ensure that:
- The tags that you are adding are case-sensitive.
- Any new tag with a key identical to that of an existing tag overwrites the existing tag.
For more information, see TagQueue.
Syntax
tagQueue(String queueUrl, Struct tags)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue which is to be tagged. |
String |
Yes |
map |
The tags to be added to the queue. |
Struct |
Yes |
For more information, see tagQueue parameters.
Example
<cfscript> sqs=getCloudService(application.awsCred, application.sqsConf) // create a queue myQueue=sqs.createQueue("QueueTags") // get url of the queue queueUrl=sqs.getQueueUrl("QueueTags") writeOutput("The queue url is: " & queueUrl) // create tags queueTags={ "tags"={ "Product":"ColdFusion", "Version":"2021", "Build":"338001", "Date":"2020/10/28", "Location":"Adobe", "Place":"Bangalore" } } try{ queueTagResponse=sqs.tagQueue(queueUrl,queueTags) writeOutput(""&"Queue successfully tagged") writeDump(queueTagResponse) } catch(any e){ writeDump(e) } </cfscript>
Using queue object
<cfscript> sqs=getCloudService(application.awsCred, application.sqsConf) // create a queue myQueue=sqs.createQueue("QueueTags") // get url of the queue queueUrl=sqs.getQueueUrl("QueueTags") writeOutput("The queue url is: " & queueUrl) // create tags queueTags={ "tags"={ "Product":"ColdFusion", "Version":"2021", "Build":"338001", "Date":"2020/10/28", "Location":"Adobe", "Place":"Bangalore" } } try{ queueTagResponse=myQueue.tag(queueTags) writeOutput(""&"Queue successfully tagged") writeDump(queueTagResponse) } catch(any e){ writeDump(e) } </cfscript>
List tags of a queue
List all tags of a specified queue.
For more information, see ListQueueTags.
Syntax
listQueueTags(queueURL)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue. |
String |
Yes |
For more information, see parameters.
Example
<cfscript> sqs=getCloudService(application.awsCred, application.sqsConf) // list queues queueList=sqs.listQueues() // get queue url of the queue created in the previous example queueUrl=queueList.queueUrls[16] tagList=sqs.listQueueTags(queueUrl) writeOutput("List of tags in the queue:") writeDump(tagList.tags) </cfscript>
The next example displays the list of tags in a queue by using the queue object. Here, a queue is created and a few tags are added to the queue.
<cfscript> sqs=getCloudService(application.awsCred, application.sqsConf) // create a queue myQueue=sqs.createQueue("QueueTags") // add tags to the queue queueTags={ "tags"={ "Product":"ColdFusion", "Version":"2021", "Build":"338001", "Date":"2020/10/28", "Location":"Adobe" } } myQueue.tag(queueTags) // list tags listTagResponse=myQueue.listQueueTags() writeDump(listTagResponse) </cfscript>
Untag a queue
You can remove a tag from the queue using the tag's key.
For more information, see Untag a queue.
Syntax
untagQueue(String queueUrl, Struct tags)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue. |
String |
Yes |
map |
Array of tags to be removed from the specified queue. |
Array |
Yes |
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); //writeoutput("Create queue in AWS<br>"); myQueue = sqs.createQueue("Tagging_Queue"); //writeoutput("set Tag queue attributes response"); tagQueueMetadata = {"tags"= { "Product"="ColdFusion", "Environment"="Production" } }; // tag the queue setQueueAttributesResponse = myQueue.tag(tagQueueMetadata); writeoutput(#myQueue.ListQueueTags().tags["Product"]#); writeoutput(#myQueue.ListQueueTags().tags["Environment"]#&"<br>"); untagQueueMetadata = {"tagKeys"=["Product","Environment"]}; // untag the queue untagQueueResponse = myQueue.untag(untagQueueMetadata); try{ writeoutput(#myQueue.ListQueueTags().tags["Environment"]#); } catch(any e){ writeoutput(e.Message); } </cfscript>
Delete a queue
Delete a queue in SQS. For more information, see Delete a queue.
You can delete a queue even when it is not empty. If you want to delete the messages in a queue but not the queue itself, you can purge the queue.
When you delete a queue, all messages in the queue are no longer available.
Syntax
deleteQueue(queueURL)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue. |
String |
Yes |
Example
<cfscript> // Get the getCloudService from the credentials and configuration we declared in Application.cfc sqs = getCloudService(application.awsCred, application.sqsConf) // Use the sqs service object to create a queue using createQueue(). This method returns a queue object. myQueue=sqs.createQueue("QueueForDeletion"); // get queue Url queueUrl=sqs.getQueueUrl("QueueForDeletion") try{ sqs.deleteQueue(queueUrl) writeOutput("Queue deleted successfully.") } catch(any e){ writeDump(e) } </cfscript>
Purge a queue
If you do not want to delete a queue, but need to delete all the messages from it, you can purge the queue.
For more information, see Purge queue.
Syntax
purgeQueue(queueURL)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue. |
String |
Yes |
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); stdQueue = sqs.createQueue("PurgeMessageQueue"); stdQueueUrl = stdQueue.getQueueUrl(); sendMessageMetadata = { "messageBody"="This is a sample message", "messageAttributes"={ "timestamps"=dateTimeFormat(now()), "geospatial_data"="San Francisco", "signatures"="ADBE", "identifiers"="ColdFusion" } } // send message to the queue sqs.sendMessage(stdQueueUrl,sendMessageMetadata) try{ sqs.purgeQueue(stdQueueUrl) writeOutput("Queue purged successfully.") } catch(any e){ writeDump(e) } </cfscript>
Send message to a queue
You can send a message to the queue that exists by specifying your AWS credentials. For more information, see Send message in SQS.
Syntax
sendMessage(String queueUrl, Struct message)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueUrl |
The URL of the queue to which a message is to be sent. |
String |
Yes |
messageAttributes |
Key-value pair of SQS message attributes. For more information, see SQS Message Attributes. |
Struct |
No |
messageBody |
The message to send to the queue. |
String |
Yes |
messageDeduplicationId |
Applies only to FIFO queues. This is a token for deduplication of messages. |
String |
No |
messageGroupId |
Applies only to FIFO queues. This is a tag for a specific message group. |
String |
No |
messageSystemAttribute |
Key-value pair of message system attributes. For more information, see SQS Message System Attributes. |
Struct |
No |
For more information, see SendMessage request parameters.
Example
Example 1- Send message to a standard queue
<cfscript> //Get the getCloudService from the credentials and configuration we declared in Application.cfc sqs = getCloudService(application.awsCred, application.sqsConf); // Use the sqs service object to create a queue using createQueue(). // This method returns a queue object. myQueue = sqs.createQueue("SimpleMessageQueue"); // Use the queue object to send a message to the queue. message = {"messageBody"="This is a sample message."}; sendMessageResponse = myQueue.sendMessage(message); writedump(sendMessageResponse) // display the status code writeoutput(sendMessageResponse.sdkHttpResponse["statusCode"]); // 200 </cfscript>
Example 2- Send message to a standard queue with additional parameters
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); stdQueue = sqs.createQueue("sendMessage"); stdQueueUrl = stdQueue.getQueueUrl(); sendMessageMetadata = { "messageBody"="This is a sample message", "messageAttributes"={ "timestamps"="#dateTimeFormat(now())#", "geospatial_data"="San Francisco", "signatures"="ADBE", "identifiers"="ColdFusion" } } sendMessageResp = sqs.sendMessage(stdQueueUrl,sendMessageMetadata); writeoutput(sendMessageResp.sdkHttpResponse.statusCode); // 200 </cfscript>
Example 3- Send message to a FIFO queue
<cfscript> try{ sqs = getCloudService(application.awsCred, application.sqsConf); queueAttributes = { "attributes" : {"FifoQueue" : "true"} } fifoQueue = sqs.createQueue("sendMessage.fifo", queueAttributes); fifoQueueUrl = fifoQueue.getQueueUrl(); sendMessageMetadata = { "messageBody"="This is a sampe message", "messageGroupId" ="12345", "messageDeduplicationId" ="123456", "messageAttributes"={ "timestamps"="#dateTimeFormat(now())#", "geospatial_data"="San Jose", "signatures"="ADBE", "identifiers"="ColdFusion" } }; // send message sendMessageResp = sqs.sendMessage(fifoQueueUrl,sendMessageMetadata); writeoutput(sendMessageResp.sdkHttpResponse.statusCode); // 200 } catch(any e){ writeDump(e); } </cfscript>
Send message with attributes
You can include structured metadata (such as timestamps, geospatial data, signatures, and identifiers) with messages using message attributes.
For more information, see Send message with attributes.
Example
<cfscript> // Get the getCloudService from the credentials and configuration we declared in Application.cfc sqs = getCloudService(application.awsCred, application.sqsConf) // Use the sqs service object to create a queue using createQueue(). This method returns a queue object. //writeoutput("Create queue in AWS<br>"); myQueue = sqs.createQueue("MessageQueueWithAttribute"); //Use the queue object to send a message to the queue. sendMessageMetadata = { "messageBody"="This is a sample message", "messageAttributes"={ "timestamps"=datetimeformat(now()), "geospatial_data"="Bangalore", "signatures"="ADBE", "identifiers"="ColdFusion" } }; sendMessageResponse = myQueue.sendMessage(sendMessageMetadata); writeoutput("message successfully sent with attribute"); writeDump(sendMessageResponse) </cfscript>
Receive message
After you send a message into a queue, you can retrieve it from the queue. When you request a message from a queue, you can't specify which message to get. Instead, you must specify the maximum number of messages (up to 10) that you want to get.
For more information, see Receive message in a queue.
Syntax
receiveMessage(String queueUrl, Map receiveMessageOptions)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueUrl |
The URL of the queue from which messages are received. |
String |
Yes |
messageAttributeNames |
One of the following:
|
Struct |
No |
maxNumberOfMessages |
The maximum number of messages to return. Valid value 1-10. |
Integer |
No |
receiveRequestAttemptId |
ONLY FOR FIFO queues. |
String |
No |
vVisibilityTimeout |
The time for which messages remain hidden from retrieve requests. |
Integer |
No |
waitTime |
The duration for which a message waits before arriving in the queue. |
Integer |
No |
For more information, see request parameters.
Example
Example 1- Receive a message in a FIFO queue
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); // define attribues for a FIFO queue queueAttributes = { "attributes" : { "FifoQueue" : "true" } } fifoQueue = sqs.createQueue("sendMessage.fifo", queueAttributes); fifoQueueUrl = fifoQueue.getQueueUrl(); sendMessageMetadata = { "messageBody"="This is a sample message", "messageGroupId" ="12345", "messageDeduplicationId" ="123456", "messageAttributes"={ "timestamps"="#dateTimeFormat(now())#", "geospatial_data"="Bangalore", "signatures"="SG", "identifiers"="ColdFusion" } } // send message sqs.sendMessage(fifoQueueUrl,sendMessageMetadata) // define receive message metadata receiveMessageMetadata = { "messageAttributeNames"="All" } try{ receiveMessageResp = sqs.receiveMessage(fifoQueueUrl,receiveMessageMetadata) writeOutput("Message received successfully") writeDump(receiveMessageResp) } catch (any e){ writeDump(e) } </cfscript>
Example 2- Send messages in a standard queue
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); // create a queue stdQueue = sqs.createQueue("ReceiveMessageQueueNew"); // get queue url stdQueueUrl = stdQueue.getQueueUrl(); sendMessageMetadata = { "messageBody"="This is a sample message", "messageAttributes"={ "timestamps"="#dateTimeFormat(now())#", "geospatial_data"="San Jose", "signatures"="SG", "identifiers"="ColdFusion" } } // send message sqs.sendMessage(stdQueueUrl,sendMessageMetadata); // define receive message metadata receiveMessageMetadata = { "messageAttributeNames"="All" } try{ receiveMessageResp = sqs.receiveMessage(stdQueueUrl,receiveMessageMetadata) writeOutput("Message received successfully") writeDump(receiveMessageResp) writeoutput(ArrayLen(receiveMessageResp.messages)>0) // TRUE } catch(any e){ writeDump(e) } </cfscript>
Delete a message
Delete a message from a queue. To select the message to delete, use the ReceiptHandle of the message.
For more information, see Delete message in a queue.
Syntax
deleteMessage(String queueUrl, Struct message)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue. |
String |
Yes |
receiptHandle |
The receipt handle associated with the message to delete. |
String |
Yes |
For more information, see request parameters.
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); // create a queue stdQueue = sqs.createQueue("ReceiveMessageQueueNew"); // get queue url stdQueueUrl = stdQueue.getQueueUrl(); sendMessageMetadata = { "messageBody"="This is a sample message", "messageAttributes"={ "timestamps"="#dateTimeFormat(now())#", "geospatial_data"="San Jose", "signatures"="SG", "identifiers"="ColdFusion" } } // send message sqs.sendMessage(stdQueueUrl,sendMessageMetadata) // receive message // define receive message metadata receiveMessageMetadata = { "messageAttributeNames"="All" } receiveMessageResp=sqs.receiveMessage(stdQueueUrl,receiveMessageMetadata) // get receipt handle receiptHandle={ "receiptHandle":receiveMessageResp.messages[1].receiptHandle } // delete message try{ deleteMessageResponse=sqs.deleteMessage(stdQueueUrl,receiptHandle) writeOutput("Message deleted successfully") writeDump(deleteMessageResponse) } catch(any e){ writeDump(e) } </cfscript>
Set attributes of a queue
Set the value of one or more queue attributes.
For more information, see Set queue attributes.
Syntax
setQueueAttributes(String queueUrl, Struct queueAttributes)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The URL of the queue whose attributes are to be set. |
String |
Yes |
attribute |
Key-value pair of the following:
Attributes for FIFO:
Attributes for Server-Side Encryption:
|
Struct |
Yes |
For more information, see request parameters.
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf) // create a queue sqs.createQueue("QueueAttributeDemo") // get queue url qURL=sqs.getQueueUrl("QueueAttributeDemo") // define queue attribute metadata setQueueAttributes = { "attributes"={ "VisibilityTimeout"="10", "MessageRetentionPeriod"="100", "MaximumMessageSize"="1024", "DelaySeconds"="10", "ReceiveMessageWaitTimeSeconds"="20" } } // set the queue attributes try{ queueAttributeResponse=sqs.setQueueAttributes(qURL,setQueueAttributes writeOutput("Queue attributes set successfully") writeDump(queueAttributeResponse) } catch(any e){ writeOutput("Unable to set queue attribute") writeDump(e) } </cfscript>
Get attributes of a queue
Get the attributes of a specified queue.
For more information, see Get queue attributes.
Syntax
getQueueAttributes(String queueUrl, Struct queueAttributes)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The URL of the queue whose attributes are to be retrieved. |
String |
Yes |
attributeNames |
One of the following:
Attributes for SSE:
Attributes for FIFO:
|
Array |
Yes |
For more information, see request parameters.
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf) // create a queue sqs.createQueue("QueueGetAttributeDemo") // get queue url qURL=sqs.getQueueUrl("QueueGetAttributeDemo") // define queue attribute metadata setQueueAttributes = { "attributes"={ "VisibilityTimeout"="10", "MessageRetentionPeriod"="100", "MaximumMessageSize"="1024", "DelaySeconds"="10", "ReceiveMessageWaitTimeSeconds"="20" } } // set the queue attributes sqs.setQueueAttributes(qURL,setQueueAttributes) // define get attribute metadata getQueueAttributesMetadata={ "attributeNames"=["All"] } try{ getAttributeResponse=sqs.getQueueAttributes(qURL,getQueueAttributesMetadata) writeOutput("Queue attributes are:") writeDump(getAttributeResponse.attributes) } catch(any e){ writeDump(e) } </cfscript>
Change message visibility
Change the visibility timeout of a message in a queue. The default visibility timeout for a message is 30 seconds. The range is 0 seconds-12 hours.
For more information, see Change message visibility.
Syntax
changeMessageVisibility(String queueUrl, Struct message)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The URL of the queue whose message's visibility timeout is to be changed. |
String |
Yes |
receiptHandle |
The receipt handle of the message whose visibility timeout is to be changed. |
String |
Yes |
visibilityTimeout |
The new timeout value (0-43200) |
Integer |
Yes |
For more information, see request parameters.
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); stdQueue = sqs.createQueue("ChangeVisibilityDemo"); stdQueueUrl = stdQueue.getQueueUrl(); sendMessageMetadata = { "messageBody"="This is a sample message", "messageAttributes"={ "timestamps"="#dateTimeFormat(now())#", "geospatial_data"="London", "signatures"="CF", "identifiers"="ColdFusion" } } // send message to the queue sqs.sendMessage(stdQueueUrl,sendMessageMetadata); // define receive message metadata receiveMessageMetadata = { "messageAttributeNames"="All" }; // receive message receiveMessageResp=sqs.receiveMessage(stdQueueUrl,receiveMessageMetadata); msgReceiptHandle= receiveMessageResp.messages[1].receiptHandle; // define change visibility metadata changeVisibilityMetadata= { "visibilityTimeout":"100", // 100 seconds "receiptHandle":msgReceiptHandle } try{ changeVisibiltyResponse= sqs.changeMessageVisibility(stdQueueUrl,changeVisibilityMetadata) writeOutput("Message visibility timeout changed successfully") writeDump(changeVisibiltyResponse) writeoutput(changeVisibiltyResponse.sdkHttpResponse.statusCode) } catch(any e){ writeDump(e) } </cfscript>
Change message visibility batch
Change visibility timeout for multiple messages.
For more information, see Change message visibility match.
Syntax
changeMessageVisibilityBatch(String queueUrl, List<Map> messages)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue whose messages' visibility is to be changed. |
String |
Yes |
changeMessageVisibilityBatchMetadata |
Receipt handles of the messages for which the visibility timeout must be changed. For more information, see the array objects. |
Array |
Yes |
For more information, see request parameters.
Example
<cfscript> sqsObj = getCloudService(application.awsCred, application.sqsConf); stdQueueName = "stdBatchQueue" // create the queue stdQueueObj = sqsObj.createQueue(stdQueueName); // get the queue url stdQueueUrl = stdQueueObj.getQueueUrl() // define the metadata for sending messages in a batch sendMessageBatchMetadata = [ { "id":"1", "messageAttributes":{ "name":"name1", "type":"string", "value":"value1" }, "messageBody":"This is the body of batch 1" }, { "id":"2", "messageAttributes":{ "name":"name2", "type":"number", "value":24 }, "messageBody":"This is the body of batch 2" }, { "id":"3", "messageAttributes":{ "name":"name3", "type":"string", "value":"value2" }, "messageBody":"This is the body of batch 3" } ] // send the messages in batch sendMessageBatchResponse = sqsObj.sendMessageBatch(stdQueueUrl, sendMessageBatchMetadata); // Receive the messages in the queue receiveMessageMetadata = { "messageAttributeNames"="All", "maxNumberOfMessages"=5 } receiveMessageResp = sqsObj.receiveMessage(stdQueueUrl,receiveMessageMetadata); writeDump(receiveMessageResp) //break; // Define metadata for visibility change changeMessageVisibilityBatchMetadata=[ { "id":receiveMessageResp.messages[1].messageId, "receiptHandle":receiveMessageResp.messages[1].receiptHandle, "visibilityTimeout":"20" } // { // "id":receiveMessageResp.messages[2].messageId, // "receiptHandle":receiveMessageResp.messages[2].receiptHandle, // "visibilityTimeout":"10" // } ] // Change visiblity in batch changeMessageVisibilityBatchResponse=sqsObj.changeMessageVisibilityBatch(stdQueueUrl,changeMessageVisibilityBatchMetadata) writeDump(changeMessageVisibilityBatchResponse) </cfscript>
Send messages in batch
Send a batch of up to 10 messages to a specified queue. This is a batch version of the sendMessage API.
For more information, see SendMessageBatch.
Syntax
sendMessageBatch(String queueUrl, List<Map> messages)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue to which messages are to be sent in a batch. |
String |
Yes |
sendMessageBatchMetadata |
Array of SendMessageBatchRequestEntry objects. |
Array |
Yes |
For more information, see request parameters.
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf) // get queue url to which the message batch will be sent. myQueueUrl=sqs.listQueues().queueUrls[1] sendMessageBatchMetadata = [ { "id":"1", "messageAttributes":{ "name":"name1", "type":"string", "value":"value1" }, "messageBody":"This is the body of batch 1" }, { "id":"2", "messageAttributes":{ "name":"name2", "type":"number", "value":24 }, "messageBody":"This is the body of batch 2" } ] try{ sendMessageBatchResponse = sqs.sendMessageBatch(myQueueUrl, sendMessageBatchMetadata) writeOutput("Message batch sent successfully") writeDump(sendMessageBatchResponse) writeDump(sendMessageBatchResponse.successful) } catch (any e){ writeDump(e) } </cfscript>
Delete messages in a batch
Delete up to 10 messages in a queue. This function is the batch version of the deleteMessage API.
For more information, see Delete messages in a batch.
Syntax
deleteMessageBatch(String queueUrl, List<Map> messages)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue whose messages are to be deleted. |
String |
Yes |
deleteMessageBatchMetadata |
List of receipt handles of the messages to be deleted. Array of DeleteMessageBatchRequestEntry objects. |
Array |
Yes |
For more information, see request parameters.
Example
Example 1- Standard queue
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf) // create a queue myQueue = sqs.createQueue("SendDeleteBatchMessage") // get queue url qURL=myQueue.getQueueUrl() // upoad a file myImage = "image.PNG" sendMessageBatchMetadata = [ {"id"="1", "messageBody"="Delete Batch Message 1", "messageAttributes"={"date"=datetimeformat(now()), "myAtt12"="#toBinary(toBase64(myImage))#"}}, {"id"="2", "messageBody"="Delete Batch Message 2", "messageAttributes"={"send_date"=datetimeformat(now())}} ]; sendMessageResponse = sqs.sendMessageBatch(qURL, sendMessageBatchMetadata) // writeDump(sendMessageResponse) // break; // receive messages in the queue receiveMessageMetadata = {"messageAttributeNames"="All","maxNumberOfMessages"=2} receiveMessageResponse = sqs.receiveMessage(qURL,receiveMessageMetadata); writeDump(receiveMessageResponse) //break; writeoutput("Delete message batch response"); msgReceiptHandle1= receiveMessageResponse.messages[1].receiptHandle; msgReceiptHandle2= receiveMessageResponse.messages[2].receiptHandle; deleteMessageBatchMetadata = [ {"id"="1", "receiptHandle"="#msgReceiptHandle1#"}, {"id"="2", "receiptHandle"="#msgReceiptHandle2#"} ]; deleteMessageResponse = sqs.deleteMessageBatch(qURL,deleteMessageBatchMetadata); writeDump(deleteMessageResponse) </cfscript>
Example 2- FIFO queue
<cfscript> try{ sqs = getCloudService(application.awsCred, application.sqsConf); queueAttributes = { "attributes" : {"FifoQueue" : "true"} } fifoQueue = sqs.createQueue("sendBatchMessage.fifo", queueAttributes); fifoQueueUrl = fifoQueue.getQueueUrl(); sendMessageBatchMetadata = [ {"id"="1", "messageBody"="First Batch message","messageGroupId" ="720","messageDeduplicationId" ="23", "messageAttributes"={"myAtt1"="First"}}, {"id"="2", "messageBody"="Second Batch Message","messageGroupId" ="008","messageDeduplicationId" ="45", "messageAttributes"={"myAtt21"="Second"}} ]; sendMessageResp = sqs.sendMessageBatch(fifoQueueUrl,sendMessageBatchMetadata); writeoutput(sendMessageResp.sdkHttpResponse.statusCode); receiveMessageMetadata = {"messageAttributeNames"="All","maxNumberOfMessages"=2}; receiveMessageResp = sqs.receiveMessage(fifoQueueUrl,receiveMessageMetadata); msgReceiptHandle1= receiveMessageResp.messages[1].receiptHandle; msgReceiptHandle2= receiveMessageResp.messages[2].receiptHandle; deleteMessageBatchMetadata = [ {"id"="1", "receiptHandle"="#msgReceiptHandle1#"}, {"id"="2", "receiptHandle"="#msgReceiptHandle2#"} ]; deleteMsgReps= sqs.deleteMessageBatch(fifoQueueUrl,deleteMessageBatchMetadata); writeoutput(deleteMsgReps.sdkHttpResponse.statusCode); } catch(any e){ writeDump(e); }
Add permission
Add permission to a queue for for a user, service, or account, whose permissions are defined in a policy.
When you create a queue, you have full control of the queue. You can then grant or deny permissions to the queue.
For more information, see Add permission.
Syntax
addPermission(String queueUrl, Struct permission)
Parameters
Parameter |
Description |
Type |
Required |
---|---|---|---|
Actions |
The action the client wants to allow for the specified principal. Valid values are:
|
Array |
Yes |
awsAccountIds |
The AWS account number of the principal who is given permission. |
Array |
Yes |
Label |
The unique id of the permission to be set. |
String |
Yes |
queueUrl |
The URL of the queue. |
String |
Yes |
For more information, see request parameters.
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); // create queue sqs.createQueue("AddPermission"); // get url of the queue queueUrl=sqs.getQueueUrl("AddPermission") // define permission struct addPermissionStruct={ "actions" = ["SendMessage"], // Send message action granted "awsAccountIds" = ["xxxxxxxxxxxxx"], "label" = "label-cf-sqs" } try{ addPermissionResp = sqs.addPermission(queueUrl,addPermissionStruct) writeOutput("Permission added successfully") writeDump(addPermissionResp) } catch (any e){ writeDump(e) } </cfscript>
Remove permission
Revoke any permissions in the policy of the queue that matches the label, which was used to add permission in the first place.
For more information, see Remove permission.
Syntax
removePermission(String queueUrl, String permissionLabel)
Parameters
Parameters |
Description |
Type |
Required |
---|---|---|---|
queueURL |
The url of the queue from which you want to remove the permission. |
String |
Yes |
permissionLabel |
The unique Id of the permission to remove. |
String |
Yes |
For more information, see request parameters.
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); // create queue sqs.createQueue("RemovePermission"); // get url of the queue queueUrl=sqs.getQueueUrl("AddPermission") // define permission struct addPermissionStruct={ "actions" = ["SendMessage"], // Send message action granted "awsAccountIds" = ["xxxxxxxxxxxxx"], "label" = "label-cf-sqs" } sqs.addPermission(queueUrl,addPermissionStruct) // remove permission struct labelToRemove="label-cf-sqs" try{ removePermissionResp = sqs.removePermission(queueUrl,labelToRemove) writeOutput("Permission removed successfully") writeDump(removePermissionResp) } catch(any e){ writeDump(e) } </cfscript>
List Dead Letter Source Queues
In SQS, using a dead letter queue, you can automatically transfer messages, that have exceeded the maximum number of receiving messages, to the dead letter queue.
Also a dead letter queue stores messages when the queue does not exist or the queue or message length have exceeded a set value.
In a nutshell, a dead letter queue handles failed messages so that you can letter debug a faulty message.
You can set a redrive policy on a queue where you can define that if a message is not successfully processed by a consumer within a specified number of times, SQS will send that message to a dead letter queue.
For more information, see Amazon dead letter queues.
The listDeadLetterSourceQueues API returns a list of your queues that have the RedrivePolicy attribute configured with a dead-letter queue.
For more information, see ListDeadLetterSourceQueues.
Syntax
listDeadLetterSourceQueues(queueUrl)
Parameters
Parameter |
Description |
Type |
Required |
queueURL |
The URL of a dead-letter queue. |
String |
Yes |
For more information, see request parameters.
Example
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); setQueueAttributesMetadata = { "attributes"={ "FifoQueue" : "true" } } // create FIFO queues myQueue = sqs.createQueue("FIFOQueue4DL.fifo",setQueueAttributesMetadata); deadLetterQueue = sqs.createQueue("dead_Letter_Queue.fifo",setQueueAttributesMetadata); queueUrl = myQueue.getQueueUrl(); getQueueAttributesMetadata = {"attributeNames":["All"]}; deadLetterQueueARN = deadLetterQueue.getAttributes(#getQueueAttributesMetadata#).attributes["QueueArn"]; redrivePolicy = { "maxReceiveCount" = 2, "deadLetterTargetArn" = "#deadLetterQueueARN#" } setQueueAttributesMetadata = { "attributes"={ "RedrivePolicy" = "#serializeJson(redrivePolicy)#" } }; setQueueAttributesResponse = myQueue.setAttributes(setQueueAttributesMetadata); getQueueAttributesMetadata = {"attributeNames"=["All"]}; getQueueAttributesResponse = myQueue.getAttributes(getQueueAttributesMetadata); redrivePolicyVal= #deserializeJson(getQueueAttributesResponse.attributes["RedrivePolicy"])#; writeoutput(#redrivePolicyVal.deadLetterTargetArn#); </cfscript>
Configure Long Polling with Queue
SQS is a poll-based service, where applications poll messages from SQS queue. If you poll your SQS queue and it returns an empty response, you are still charged. The default polling for SQS is short polling, where the response is sent without any wait time even if the queue is empty or updated with new messages.
Long polling eliminates the number of empty responses and false empty responses, when messages are available, but aren’t included in a response.
For more information, see Long polling for SQS.
<cfscript> sqs = getCloudService(application.awsCred, application.sqsConf); myQueue = sqs.createQueue("longPolling"); writeoutput(myQueue.getQueueUrl()); queueUrl = myQueue.getQueueUrl(); setQueueAttributesMetadata = { "attributes"={ "ReceiveMessageWaitTimeSeconds"="20" } }; setQueueAttributesResponse = myQueue.setAttributes(setQueueAttributesMetadata); longPollingVal=myQueue.getAttributes({"attributeNames"=["ReceiveMessageWaitTimeSeconds"]}); writeoutput(longPollingVal.attributes["ReceiveMessageWaitTimeSeconds"]); </cfscript>
Adobe
Recevez de l’aide plus rapidement et plus facilement
Nouvel utilisateur ?