Quarkus - Using the Redis Client

This guide demonstrates how your Quarkus application can connect to a Redis server using the Redis Client extension.

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.

Prerequisites

To complete this guide, you need:

  • less than 15 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.5.3+

  • A running Redis server, or Docker Compose to start one

  • GraalVM installed if you want to run in native mode.

Architecture

In this guide, we are going to expose a simple Rest API to increment numbers by using the INCRBY command. Along the way, we’ll see how to use other Redis commands like GET, SET, DEL and KEYS.

We’ll be using the Quarkus Redis Client extension to connect to our Redis Server. The extension is implemented on top of the Vert.x Redis Client, providing an asynchronous and non-blocking way to connect to Redis.

Solution

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 redis-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=redis-quickstart \
  4. -Dextensions="redis-client, resteasy-jsonb, resteasy-mutiny"
  5. cd redis-quickstart

This command generates a Maven project, importing the Redis extension.

If you already have your Quarkus project configured, you can add the redis-client extension to your project by running the following command in your project base directory:

  1. ./mvnw quarkus:add-extension -Dextensions="redis-client"

This will add the following to your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-redis-client</artifactId>
  4. </dependency>

Starting the Redis server

Then, we need to start a Redis instance (if you do not have one already) using the following command:

  1. docker run --ulimit memlock=-1:-1 -it --rm=true --memory-swappiness=0 --name redis_quarkus_test -p 6379:6379 redis:5.0.6

Configuring Redis properties

Once we have the Redis server running, we need to configure the Redis connection properties. This is done in the application.properties configuration file. Edit it to the following content:

  1. quarkus.redis.hosts=localhost:6379 (1)
  1. Configure Redis hosts to connect to. Here we connect to the Redis server we started in the previous section

Creating the Increment POJO

We are going to model our increments using the Increment POJO. Create the src/main/java/org/acme/redis/Increment.java file, with the following content:

  1. package org.acme.redis;
  2. public class Increment {
  3. public String key; (1)
  4. public int value; (2)
  5. public Increment(String key, int value) {
  6. this.key = key;
  7. this.value = value;
  8. }
  9. public Increment() {
  10. }
  11. }
  1. The key that will be used as the Redis key

  2. The value held by the Redis key

Creating the Increment Service

We are going to create an IncrementService class which will play the role of a Redis client. With this class, we’ll be able to perform the SET, GET , DELET, KEYS and INCRBY Redis commands.

Create the src/main/java/org/acme/redis/IncrementService.java file, with the following content:

  1. package org.acme.redis;
  2. import io.quarkus.redis.client.RedisClient;
  3. import io.quarkus.redis.client.reactive.ReactiveRedisClient;
  4. import io.smallrye.mutiny.Uni;
  5. import io.vertx.mutiny.redis.client.Response;
  6. import java.util.ArrayList;
  7. import java.util.Arrays;
  8. import java.util.List;
  9. import javax.inject.Inject;
  10. import javax.inject.Singleton;
  11. @Singleton
  12. class IncrementService {
  13. @Inject
  14. RedisClient redisClient; (1)
  15. @Inject
  16. ReactiveRedisClient reactiveRedisClient; (2)
  17. Uni<Void> del(String key) {
  18. return reactiveRedisClient.del(Arrays.asList(key))
  19. .map(response -> null);
  20. }
  21. String get(String key) {
  22. return redisClient.get(key).toString();
  23. }
  24. void set(String key, Integer value) {
  25. redisClient.set(Arrays.asList(key, value.toString()));
  26. }
  27. void increment(String key, Integer incrementBy) {
  28. redisClient.incrby(key, incrementBy.toString());
  29. }
  30. Uni<List<String>> keys() {
  31. return reactiveRedisClient
  32. .keys("*")
  33. .map(response -> {
  34. List<String> result = new ArrayList<>();
  35. for (Response r : response) {
  36. result.add(r.toString());
  37. }
  38. return result;
  39. });
  40. }
  41. }
  1. Inject the Redis synchronous client

  2. Inject the Reactive Redis client

Creating the Increment Resource

Create the src/main/java/org/acme/redis/IncrementResource.java file, with the following content:

  1. package org.acme.redis;
  2. import javax.inject.Inject;
  3. import javax.ws.rs.GET;
  4. import javax.ws.rs.PathParam;
  5. import javax.ws.rs.PUT;
  6. import javax.ws.rs.Consumes;
  7. import javax.ws.rs.Produces;
  8. import javax.ws.rs.Path;
  9. import javax.ws.rs.POST;
  10. import javax.ws.rs.DELETE;
  11. import javax.ws.rs.core.MediaType;
  12. import java.util.List;
  13. import io.smallrye.mutiny.Uni;
  14. @Path("/increments")
  15. @Produces(MediaType.APPLICATION_JSON)
  16. @Consumes(MediaType.APPLICATION_JSON)
  17. public class IncrementResource {
  18. @Inject
  19. IncrementService service;
  20. @GET
  21. public Uni<List<String>> keys() {
  22. return service.keys();
  23. }
  24. @POST
  25. public Increment create(Increment increment) {
  26. service.set(increment.key, increment.value);
  27. return increment;
  28. }
  29. @GET
  30. @Path("/{key}")
  31. public Increment get(@PathParam("key") String key) {
  32. return new Increment(key, Integer.valueOf(service.get(key)));
  33. }
  34. @PUT
  35. @Path("/{key}")
  36. public void increment(@PathParam("key") String key, Integer value) {
  37. service.increment(key, value);
  38. }
  39. @DELETE
  40. @Path("/{key}")
  41. public Uni<Void> delete(@PathParam("key") String key) {
  42. return service.del(key);
  43. }
  44. }

Modifying the test class

Edit the src/test/java/org/acme/redis/IncrementResourceTest.java file to the following content:

  1. package org.acme.redis;
  2. import static org.hamcrest.Matchers.is;
  3. import org.junit.jupiter.api.Test;
  4. import io.quarkus.test.junit.QuarkusTest;
  5. import static io.restassured.RestAssured.given;
  6. import io.restassured.http.ContentType;
  7. @QuarkusTest
  8. public class IncrementResourceTest {
  9. @Test
  10. public void testRedisOperations() {
  11. // verify that we have nothing
  12. given()
  13. .accept(ContentType.JSON)
  14. .when()
  15. .get("/increments")
  16. .then()
  17. .statusCode(200)
  18. .body("size()", is(0));
  19. // create a first increment key with an initial value of 0
  20. given()
  21. .contentType(ContentType.JSON)
  22. .accept(ContentType.JSON)
  23. .body("{\"key\":\"first-key\",\"value\":0}")
  24. .when()
  25. .post("/increments")
  26. .then()
  27. .statusCode(200)
  28. .body("key", is("first-key"))
  29. .body("value", is(0));
  30. // create a second increment key with an initial value of 10
  31. given()
  32. .contentType(ContentType.JSON)
  33. .accept(ContentType.JSON)
  34. .body("{\"key\":\"second-key\",\"value\":10}")
  35. .when()
  36. .post("/increments")
  37. .then()
  38. .statusCode(200)
  39. .body("key", is("second-key"))
  40. .body("value", is(10));
  41. // increment first key by 1
  42. given()
  43. .contentType(ContentType.JSON)
  44. .body("1")
  45. .when()
  46. .put("/increments/first-key")
  47. .then()
  48. .statusCode(204);
  49. // verify that key has been incremented
  50. given()
  51. .accept(ContentType.JSON)
  52. .when()
  53. .get("/increments/first-key")
  54. .then()
  55. .statusCode(200)
  56. .body("key", is("first-key"))
  57. .body("value", is(1));
  58. // increment second key by 1000
  59. given()
  60. .contentType(ContentType.JSON)
  61. .body("1000")
  62. .when()
  63. .put("/increments/second-key")
  64. .then()
  65. .statusCode(204);
  66. // verify that key has been incremented
  67. given()
  68. .accept(ContentType.JSON)
  69. .when()
  70. .get("/increments/second-key")
  71. .then()
  72. .statusCode(200)
  73. .body("key", is("second-key"))
  74. .body("value", is(1010));
  75. // verify that we have two keys in registered
  76. given()
  77. .accept(ContentType.JSON)
  78. .when()
  79. .get("/increments")
  80. .then()
  81. .statusCode(200)
  82. .body("size()", is(2));
  83. // delete first key
  84. given()
  85. .accept(ContentType.JSON)
  86. .when()
  87. .delete("/increments/first-key")
  88. .then()
  89. .statusCode(204);
  90. // verify that we have one key left after deletion
  91. given()
  92. .accept(ContentType.JSON)
  93. .when()
  94. .get("/increments")
  95. .then()
  96. .statusCode(200)
  97. .body("size()", is(1));
  98. // delete second key
  99. given()
  100. .accept(ContentType.JSON)
  101. .when()
  102. .delete("/increments/second-key")
  103. .then()
  104. .statusCode(204);
  105. // verify that there is no key left
  106. given()
  107. .accept(ContentType.JSON)
  108. .when()
  109. .get("/increments")
  110. .then()
  111. .statusCode(200)
  112. .body("size()", is(0));
  113. }
  114. }

Get it running

If you followed the instructions, you should have the Redis server running. Then, you just need to run the application using:

  1. ./mvnw quarkus:dev

Open another terminal and run the curl [http://localhost:8080/increments](http://localhost:8080/increments) command.

Interacting with the application

As we have seen above, the API exposes five Rest endpoints. In this section we are going to see how to initialise an increment, see the list of current increments, incrementing a value given its key, retrieving the current value of an increment, and finally deleting a key.

Creating a new increment

  1. curl -X POST -H "Content-Type: application/json" -d '{"key":"first","value":10}' http://localhost:8080/increments (1)
  1. We create the first increment, with the key first and an initial value of 10.

Running the above command should return the result below:

  1. {
  2. "key": "first",
  3. "value": 10
  4. }

See current increments keys

To see the list of current increments keys, run the following command:

  1. curl http://localhost:8080/increments

The above command should return ["first"] indicating that we have only one increment thus far.

Retrieve a new increment

To retrieve an increment using its key, we will have to run the below command:

  1. curl http://localhost:8080/increments/first (1)
  1. Running this command, should return the following result:
  1. {
  2. "key": "first",
  3. "value": 10
  4. }

Increment a value given its key

To increment a value, run the following command:

  1. curl -X PUT -H "Content-Type: application/json" -d '27' http://localhost:8080/increments/first (1)
  1. Increment the first value by 27.

Now, running the command curl [http://localhost:8080/increments/first](http://localhost:8080/increments/first) should return the following result:

  1. {
  2. "key": "first",
  3. "value": 37 (1)
  4. }
  1. We see that the value of the first key is now 37 which is exactly the result of 10 + 27, quick maths.

Deleting a key

Use the command below, to delete an increment given its key.

  1. curl -X DELETE http://localhost:8080/increments/first (1)
  1. Delete the first increment.

Now, running the command curl [http://localhost:8080/increments](http://localhost:8080/increments) should return an empty list []

Packaging and running in JVM mode

You can run the application as a conventional jar file.

First, we will need to package it:

  1. ./mvnw package
This command will start a Redis instance to execute the tests. Thus your Redis containers need to be stopped.

Then run it:

  1. java -jar ./target/redis-quickstart-1.0-SNAPSHOT-runner.jar

Running Native

You can also create a native executable from this application without making any source code changes. A native executable removes the dependency on the JVM: everything needed to run the application on the target platform is included in the executable, allowing the application to run with minimal resource overhead.

Compiling a native executable takes a bit longer, as GraalVM performs additional steps to remove unnecessary codepaths. Use the native profile to compile a native executable:

  1. ./mvnw package -Pnative

Once the build is finished, you can run the executable with:

  1. ./target/redis-quickstart-1.0-SNAPSHOT-runner

Connection Health Check

If you are using the quarkus-smallrye-health extension, quarkus-vertx-redis will automatically add a readiness health check to validate the connection to the Redis server.

So when you access the /health/ready endpoint of your application you will have information about the connection validation status.

This behavior can be disabled by setting the quarkus.redis.health.enabled property to false in your application.properties.

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.