- What you’ll build
- What you’ll need
- Create a domain class
- Create a configuration class with Spring Beans supporting reactive Redis operations
- Create a Spring Bean to load some sample data to our application when we start it
- Create a RestController to provide an external interface for our application
- Make the application executable
- Test the application
- Summary
This guide walks you through the process of creating a functional reactive application that uses Spring Data to interact with Redis using the non-blocking Lettuce driver.
You’ll build a Spring application that uses Spring Data Redis and Project Reactor to interact with a Redis data store reactively, storing and retrieving Coffee
objects without blocking. This application uses Reactor’s Publisher
implementations based upon the Reactive Streams specification, namely Mono
(for a Publisher returning 0 or 1 value) and Flux
(for a Publisher returning 0 to n values).
Create a class representing a type of coffee we wish to stock in our coffee catalog.
src/main/java/hello/Coffee.java
link:complete/src/main/java/hello/Coffee.java[role=include]
Note
|
I use Lombok in this example to eliminate the boilerplate code for constructors and so-called "data class" methods ( accessors/mutators, equals() , toString() , & hashCode() ).
|
src/main/java/hello/CoffeeConfiguration.java
link:complete/src/main/java/hello/CoffeeConfiguration.java[role=include]
Note
|
Since we may (re)start our application multiple times, we should first remove any data that may still exist from previous executions. We do this with a flushAll() (Redis) server command. Once we’ve flushed any existing data, we create a small Flux , map each coffee name to a Coffee object, and save it to the reactive Redis repository. We then query the repo for all values and display them.
|
src/main/java/hello/CoffeeLoader.java
link:complete/src/main/java/hello/CoffeeLoader.java[role=include]
src/main/java/hello/CoffeeController.java
link:complete/src/main/java/hello/CoffeeController.java[role=include]
Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main()
method. Along the way, you use Spring’s support for embedding the Netty asynchronous "container" as the HTTP runtime instead of deploying to an external instance.
src/main/java/hello/Application.java
link:complete/src/main/java/hello/Application.java[role=include]
Now that the application is running, you can test it by accessing http://localhost:8080/coffees
from HTTPie, curl, or your favorite browser.
Congratulations! You’ve just developed a Spring application that uses Spring Data and Redis for fully reactive, non-blocking database access!