Quarkus - Amazon SQS Client

Amazon Simple Queue Service (SQS) is a fully managed message queuing service. Using SQS, you can send, store, and receive messages between software components at any volume, without losing messages or requiring other services to be available. SQS offers two types of message queues. Standard queues offer maximum throughput, best-effort ordering and at-least-once delivery. SQS FIFO queues are designed to guarantee that messages are processes exactly once, on the exact order that they were sent.

You can find more information about SQS at the Amazon SQS website.

The SQS extension is based on AWS Java SDK 2.x. It’s a major rewrite of the 1.x code base that offers two programming models (Blocking & Async).

This technology is considered preview.

In preview, backward compatibility and presence in the ecosystem is not guaranteed. Specific improvements might require to change configuration or APIs and plans to become stable are under way. Feedback is welcome on our mailing list or as issues in our GitHub issue tracker.

For a full list of possible extension statuses, check our FAQ entry.

The Quarkus extension supports two programming models:

  • Blocking access using URL Connection HTTP client (by default) or the Apache HTTP Client

  • Asynchronous programming based on JDK’s CompletableFuture objects and the Netty HTTP client.

In this guide, we see how you can get your REST services to use SQS locally and on AWS.

Prerequisites

To complete this guide, you need:

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • an IDE

  • Apache Maven 3.6.2+

  • An AWS Account to access the SQS service

  • Docker for your system to run SQS locally for testing purposes

Set up SQS locally

The easiest way to start working with SQS is to run a local instance as a container.

  1. docker run --rm --name local-sqs -p 8010:4576 -e SERVICES=sqs -e START_WEB=0 -d localstack/localstack:0.11.1

This starts a SQS instance that is accessible on port 8010.

Create an AWS profile for your local instance using AWS CLI:

  1. $ aws configure --profile localstack
  2. AWS Access Key ID [None]: test-key
  3. AWS Secret Access Key [None]: test-secret
  4. Default region name [None]: us-east-1
  5. Default output format [None]:

Create a SQS queue

Create a SQS queue using AWS CLI and store in QUEUE_URL environment variable.

  1. QUEUE_URL=`aws sqs create-queue --queue-name=ColliderQueue --profile localstack --endpoint-url=http://localhost:8010`

Or, if you want to use your SQS queue on your AWS account create a queue using your default profile

  1. QUEUE_URL=`aws sqs create-queue --queue-name=ColliderQueue`

Solution

The application built here allows shooting an elementary particles (quarks) into a ColliderQueue queue of the AWS SQS. Additionally, we create a resource that allows receiving those quarks from the ColliderQueue queue in the order they were sent.

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution is located in the amazon-sqs-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=amazon-sqs-quickstart \
  4. -DclassName="org.acme.sqs.QuarksCannonSyncResource" \
  5. -Dpath="/sync-cannon" \
  6. -Dextensions="resteasy-jsonb,amazon-sqs,resteasy-mutiny"
  7. cd amazon-sqs-quickstart

This command generates a Maven structure importing the RESTEasy/JAX-RS, Mutiny and Amazon SQS Client extensions. After this, the amazon-sqs extension has been added to your pom.xml as well as the Mutiny support for RESTEasy.

Creating JSON REST service

In this example, we will create an application that sends quarks via the queue. The example application will demonstrate the two programming models supported by the extension.

First, let’s create the Quark bean as follows:

  1. package org.acme.sqs.model;
  2. import io.quarkus.runtime.annotations.RegisterForReflection;
  3. import java.util.Objects;
  4. @RegisterForReflection
  5. public class Quark {
  6. private String flavor;
  7. private String spin;
  8. public Quark() {
  9. }
  10. public String getFlavor() {
  11. return flavor;
  12. }
  13. public void setFlavor(String flavor) {
  14. this.flavor = flavor;
  15. }
  16. public String getSpin() {
  17. return spin;
  18. }
  19. public void setSpin(String spin) {
  20. this.spin = spin;
  21. }
  22. @Override
  23. public boolean equals(Object obj) {
  24. if (!(obj instanceof Quark)) {
  25. return false;
  26. }
  27. Quark other = (Quark) obj;
  28. return Objects.equals(other.flavor, this.flavor);
  29. }
  30. @Override
  31. public int hashCode() {
  32. return Objects.hash(this.flavor);
  33. }
  34. }

Then, create a org.acme.sqs.QuarksCannonSyncResource that will provide an API to shoot quarks into the SQS queue using the synchronous client.

  1. package org.acme.sqs;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.fasterxml.jackson.databind.ObjectWriter;
  4. import javax.inject.Inject;
  5. import javax.ws.rs.Consumes;
  6. import javax.ws.rs.POST;
  7. import javax.ws.rs.Path;
  8. import javax.ws.rs.Produces;
  9. import javax.ws.rs.core.MediaType;
  10. import javax.ws.rs.core.Response;
  11. import org.acme.sqs.model.Quark;
  12. import org.eclipse.microprofile.config.inject.ConfigProperty;
  13. import org.jboss.logging.Logger;
  14. import software.amazon.awssdk.services.sqs.SqsClient;
  15. import software.amazon.awssdk.services.sqs.model.SendMessageResponse;
  16. @Path("/sync/cannon")
  17. @Produces(MediaType.TEXT_PLAIN)
  18. public class QuarksCannonSyncResource {
  19. private static final Logger LOGGER = Logger.getLogger(QuarksCannonSyncResource.class);
  20. @Inject
  21. SqsClient sqs;
  22. @ConfigProperty(name = "queue.url")
  23. String queueUrl;
  24. static ObjectWriter QUARK_WRITER = new ObjectMapper().writerFor(Quark.class);
  25. @POST
  26. @Path("/shoot")
  27. @Consumes(MediaType.APPLICATION_JSON)
  28. public Response sendMessage(Quark quark) throws Exception {
  29. String message = QUARK_WRITER.writeValueAsString(quark);
  30. SendMessageResponse response = sqs.sendMessage(m -> m.queueUrl(queueUrl).messageBody(message));
  31. LOGGER.infov("Fired Quark[{0}, {1}}]", quark.getFlavor(), quark.getSpin());
  32. return Response.ok().entity(response.messageId()).build();
  33. }
  34. }

Because of the fact messages sent to the queue must be a String, we’re using Jackson’s ObjectWriter in order to serialize our Quark objects into a String.

Now, create the org.acme.QuarksShieldSyncResource REST resources that provides an endpoint to read the messages from the ColliderQueue queue.

  1. package org.acme.sqs;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.fasterxml.jackson.databind.ObjectReader;
  4. import java.util.List;
  5. import java.util.stream.Collectors;
  6. import javax.inject.Inject;
  7. import javax.ws.rs.Consumes;
  8. import javax.ws.rs.GET;
  9. import javax.ws.rs.Path;
  10. import javax.ws.rs.Produces;
  11. import javax.ws.rs.core.MediaType;
  12. import org.acme.sqs.model.Quark;
  13. import org.eclipse.microprofile.config.inject.ConfigProperty;
  14. import org.jboss.logging.Logger;
  15. import software.amazon.awssdk.services.sqs.SqsClient;
  16. import software.amazon.awssdk.services.sqs.model.Message;
  17. @Path("/sync/shield")
  18. public class QuarksShieldSyncResource {
  19. private static final Logger LOGGER = Logger.getLogger(QuarksShieldSyncResource.class);
  20. @Inject
  21. SqsClient sqs;
  22. @ConfigProperty(name = "queue.url")
  23. String queueUrl;
  24. static ObjectReader QUARK_READER = new ObjectMapper().readerFor(Quark.class);
  25. @GET
  26. @Consumes(MediaType.APPLICATION_JSON)
  27. @Produces(MediaType.APPLICATION_JSON)
  28. public List<Quark> receive() {
  29. List<Message> messages = sqs.receiveMessage(m -> m.maxNumberOfMessages(10).queueUrl(queueUrl)).messages();
  30. return messages.stream()
  31. .map(Message::body)
  32. .map(this::toQuark)
  33. .collect(Collectors.toList());
  34. }
  35. private Quark toQuark(String message) {
  36. Quark quark = null;
  37. try {
  38. quark = QUARK_READER.readValue(message);
  39. } catch (Exception e) {
  40. LOGGER.error("Error decoding message", e);
  41. throw new RuntimeException(e);
  42. }
  43. return quark;
  44. }
  45. }

We are using here a Jackson’s ObjectReader in order to deserialize queue messages into our Quark POJOs.

Configuring SQS clients

Both SQS clients (sync and async) are configurable via the application.properties file that can be provided in the src/main/resources directory. Additionally, you need to add to the classpath a proper implementation of the sync client. By default the extension uses the URL connection HTTP client, so you need to add a URL connection client dependency to the pom.xml file:

  1. <dependency>
  2. <groupId>software.amazon.awssdk</groupId>
  3. <artifactId>url-connection-client</artifactId>
  4. </dependency>

If you want to use Apache HTTP client instead, configure it as follows:

  1. quarkus.sqs.sync-client.type=apache

And add the following dependency to the application pom.xml:

  1. <dependency>
  2. <groupId>software.amazon.awssdk</groupId>
  3. <artifactId>apache-client</artifactId>
  4. </dependency>

If you’re going to use a local SQS instance, configure it as follows:

  1. quarkus.sqs.endpoint-override=http://localhost:8010
  2. quarkus.sqs.aws.region=us-east-1
  3. quarkus.sqs.aws.credentials.type=static
  4. quarkus.sqs.aws.credentials.static-provider.access-key-id=test-key
  5. quarkus.sqs.aws.credentials.static-provider.secret-access-key=test-secret
  • quarkus.sqs.aws.region - It’s required by the client, but since you’re using a local SQS instance use us-east-1 as it’s a default region of localstack’s SQS.

  • quarkus.sqs.aws.credentials.type - Set static credentials provider with any values for access-key-id and secret-access-key

  • quarkus.sqs.endpoint-override - Override the SQS client to use a local instance instead of an AWS service

If you want to work with an AWS account, you can simply remove or comment out all SQS related properties. By default, the SQS client extension will use the default credentials provider chain that looks for credentials in this order:

  • Java System Properties - aws.accessKeyId and aws.secretAccessKey

  • Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY

  • Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI

  • Credentials delivered through the Amazon ECS if the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable is set and the security manager has permission to access the variable,

  • Instance profile credentials delivered through the Amazon EC2 metadata service

And the region from your AWS CLI profile will be used.

Next steps

Packaging

Packaging your application is as simple as ./mvnw clean package. It can be run with java -Dqueue.url=$QUEUE_URL -jar target/amazon-sqs-quickstart-1.0-SNAPSHOT-runner.jar.

With GraalVM installed, you can also create a native executable binary: ./mvnw clean package -Dnative. Depending on your system, that will take some time.

Going asynchronous

Thanks to the AWS SDK v2.x used by the Quarkus extension, you can use the asynchronous programming model out of the box.

Create a org.acme.sqs.QuarksCannonAsyncResource REST resource that will be similar to our QuarksCannonSyncResource but using an asynchronous programming model.

  1. package org.acme.sqs;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.fasterxml.jackson.databind.ObjectWriter;
  4. import io.smallrye.mutiny.Uni;
  5. import javax.inject.Inject;
  6. import javax.ws.rs.Consumes;
  7. import javax.ws.rs.POST;
  8. import javax.ws.rs.Path;
  9. import javax.ws.rs.Produces;
  10. import javax.ws.rs.core.MediaType;
  11. import javax.ws.rs.core.Response;
  12. import org.acme.sqs.model.Quark;
  13. import org.eclipse.microprofile.config.inject.ConfigProperty;
  14. import org.jboss.logging.Logger;
  15. import software.amazon.awssdk.services.sqs.SqsAsyncClient;
  16. import software.amazon.awssdk.services.sqs.model.SendMessageResponse;
  17. @Path("/async/cannon")
  18. @Produces(MediaType.APPLICATION_JSON)
  19. @Consumes(MediaType.APPLICATION_JSON)
  20. public class QuarksCannonAsyncResource {
  21. private static final Logger LOGGER = Logger.getLogger(QuarksCannonAsyncResource.class);
  22. @Inject
  23. SqsAsyncClient sqs;
  24. @ConfigProperty(name = "queue.url")
  25. String queueUrl;
  26. static ObjectWriter QUARK_WRITER = new ObjectMapper().writerFor(Quark.class);
  27. @POST
  28. @Path("/shoot")
  29. @Consumes(MediaType.APPLICATION_JSON)
  30. public Uni<Response> sendMessage(Quark quark) throws Exception {
  31. String message = QUARK_WRITER.writeValueAsString(quark);
  32. return Uni.createFrom()
  33. .completionStage(sqs.sendMessage(m -> m.queueUrl(queueUrl).messageBody(message)))
  34. .onItem().invoke(item -> LOGGER.infov("Fired Quark[{0}, {1}}]", quark.getFlavor(), quark.getSpin()))
  35. .onItem().transform(SendMessageResponse::messageId)
  36. .onItem().transform(id -> Response.ok().entity(id).build());
  37. }
  38. }

We create Uni instances from the CompletionStage objects returned by the asynchronous SQS client, and then transform the emitted item.

And the corresponding async receiver of the queue messages org.acme.sqs.QuarksShieldAsyncResource

  1. package org.acme.sqs;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.fasterxml.jackson.databind.ObjectReader;
  4. import io.smallrye.mutiny.Uni;
  5. import java.util.List;
  6. import java.util.stream.Collectors;
  7. import javax.inject.Inject;
  8. import javax.ws.rs.Consumes;
  9. import javax.ws.rs.GET;
  10. import javax.ws.rs.Path;
  11. import javax.ws.rs.Produces;
  12. import javax.ws.rs.core.MediaType;
  13. import org.acme.sqs.model.Quark;
  14. import org.eclipse.microprofile.config.inject.ConfigProperty;
  15. import org.jboss.logging.Logger;
  16. import software.amazon.awssdk.services.sqs.SqsAsyncClient;
  17. import software.amazon.awssdk.services.sqs.model.Message;
  18. import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse;
  19. @Path("/async/shield")
  20. public class QuarksShieldAsyncResource {
  21. private static final Logger LOGGER = Logger.getLogger(QuarksShieldAsyncResource.class);
  22. @Inject
  23. SqsAsyncClient sqs;
  24. @ConfigProperty(name = "queue.url")
  25. String queueUrl;
  26. static ObjectReader QUARK_READER = new ObjectMapper().readerFor(Quark.class);
  27. @GET
  28. @Consumes(MediaType.APPLICATION_JSON)
  29. @Produces(MediaType.APPLICATION_JSON)
  30. public Uni<List<Quark>> receive() {
  31. return Uni.createFrom()
  32. .completionStage(sqs.receiveMessage(m -> m.maxNumberOfMessages(10).queueUrl(queueUrl)))
  33. .onItem().transform(ReceiveMessageResponse::messages)
  34. .onItem().transform(m -> m.stream().map(Message::body).map(this::toQuark).collect(Collectors.toList()));
  35. }
  36. private Quark toQuark(String message) {
  37. Quark quark = null;
  38. try {
  39. quark = QUARK_READER.readValue(message);
  40. } catch (Exception e) {
  41. LOGGER.error("Error decoding message", e);
  42. throw new RuntimeException(e);
  43. }
  44. return quark;
  45. }
  46. }

And we need to add the Netty HTTP client dependency to the pom.xml:

  1. <dependency>
  2. <groupId>software.amazon.awssdk</groupId>
  3. <artifactId>netty-nio-client</artifactId>
  4. </dependency>

Configuration Reference

About the Duration format

The format for durations uses the standard java.time.Duration format. You can learn more about it in the Duration#parse() javadoc.

You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, PT is implicitly prepended to the value to obtain a standard java.time.Duration format.

About the MemorySize format

A size configuration option recognises string in this format (shown as a regular expression): [0-9]+[KkMmGgTtPpEeZzYy]?. If no suffix is given, assume bytes.