,

Spring Data MongoDB has been updated to leverage the reactive programming model introduced in Spring Framework 5. This was followed by support for reactive data access for NoSQL databases, such as MongoDB, Cassandra, and Redis.

With the rise in popularity of NoSQL databases, MongoDB has rapidly gained popularity in the enterprise and the Spring community.

I have published both a post and a video for setting up MongoDB within a Spring Boot application.

In this post, we’ll take a look at using the reactive programming features in Spring Framework 5 and Spring Data MongoDB.

If you’re new to Reactive programming, I’ll suggest you first go through What are Reactive Streams in Java? post, followed by the Spring Web Reactive post.

The Maven POM

For this post, I’m using Embedded MongoDB. I want the benefit of talking to an instance loaded in memory with the same capabilities as my production environment. This makes development and testing blazing fast.

You can check my post to configure and use Embedded MongoDB in a Spring Boot application here.

The dependency to bring in the Embedded MongoDB is this.

The whole capability of Reactive MongoDB lies on the MongoDB driver. The official MongoDB Reactive Streams Java Driver implements the Reactive Streams API for interoperability with other reactive stream implementations. The reactive driver provides asynchronous stream processing with non-blocking back pressure for MongoDB.

To use the driver, add this dependency.

Here is the complete pom.xml.

pom.xml

The Domain Object

I have written a Product domain object for this post. Products have a name, description, price, and product URL. 

Product.java

Spring Data MongoDB Reactive CRUD Repository

If you have worked with Spring Data in a Spring Boot application, you are familar with the repository pattern.  You extend CrudRepository or its sub interface, and Spring Data MongoDB will generate the implementation for you.

Reactive repositories work the same way. You extend your repository interface from ReactiveCrudRepository, specify domain-specific query methods, and rely on Spring Data MongoDB to provide the implementations.

ReactiveCrudRepository uses reactive types introduced in Spring Framework 5. These are  Mono and Flux which implement Reactive Streams.

Here is reactive repository interface.

ReactiveProductRepository.java

As you can see, in this ReactiveProductRepository interface, the repository uses reactive types as return types.

Reactive repositories in Spring Data MongoDB can also use reactive types for parameters. The overloaded findByName() and findByNameAndImageUrl() methods are examples of this.

Configuration for Spring Data MongoDB Reactive Repositories

The configuration class is similar to a non-reactive one. Along with some infrastructural setup, we have the @EnableReactiveMongoRepositories annotation that activates support for reactive Spring Data.

The code of the ApplicationConfiguration class is this.

ApplicationConfiguration.java

This ApplicationConfiguration class extends AbstractReactiveMongoConfiguration, the base class for reactive Spring Data MongoDB configuration. The mongoClient() method is annotated with @Bean to explicitly declare a configurable MongoClient bean that represents a pool of connections for MongoDB.

Spring Data MongoDB Integration Tests

Let’s write few integration tests for the repository layer to verify that our code is using reactive MongoDB as expected.

Here is the integration test code:

ReactiveProductRepositoryIntegrationTest.java

In the test class, we autowired in two Spring Beans.

Our ReactiveProductRepository implementation that Spring Data MongoDB provides and a ReactiveMongoOperations implementation.

ReactiveMongoOperations is the interface for the main reactive Template API class, ReactiveMongoTemplate. This interface defines a basic set of reactive data access operations using Project Reactor Mono and Flux reactive types.

ReactiveMongoOperations contains reactive counterpart for most of the operations available in the MongoOperations interface of the traditional blocking template API.

The setup portion of our integration test will drop any existing documents and re-create the Product collection. The setup method then inserts 4 new documents into our MongoDB collection.

We’re calling the .block()  method to ensure processing completes before the next command is executed.

Here is the output of the Integration tests from IntelliJ:

Test Output from Spring Data MongoDB reactive tests

You can get the complete source code for this post here.

1
Share
,

An exciting feature in Spring Framework 5 is the new Web Reactive framework for allows reactive web applications. Reactive programming is about developing systems that are fully reactive and non-blocking. Such systems are suitable for event-loop style processing that can scale with a small number of threads.

Spring Framework 5 embraces Reactive Streams to enable developing systems based on the Reactive Manifesto published in 2014.

The Spring Web Reactive framework stands separately from Spring MVC. This is because Spring MVC is developed around the Java Servlet API, which uses blocking code inside of Java. While popular Java application servers such as Tomcat and Jetty, have evolved to offer non-blocking operations, the Java Servlet API has not.

From a programming perspective, reactive programming involves a major shift from imperative style logic to a declarative composition of asynchronous logic.

In this post, I’ll explain how to develop a Web Reactive application with the Spring Framework 5.0.

Spring Web Reactive Types

Under the covers, Spring Web Reactive is using Reactor, which is a Reactive Streams Implementation. The Spring Framework extends the Reactive Streams Publisher interface with the Flux and Mono  reactive types.

The Flux  data type represents zero to many objects. (0..N)

While the Mono  data type is zero to one.  (0..1)

If you’d like a deeper dive on reactive types, check on Understanding Reactive Types by Sebastien Deleuze.

The Web Reactive Application

The application that we will create is a web reactive application that performs operations on domain objects. To keep it simple, we will use an in memory repository implementation to simulate CRUD operations in this post. In latter posts, we will go reactive with Spring Data.

Spring 5 added the new spring-webflux module for reactive programming that we will use in our application. The application is composed of these components:

  • Domain object: Product in our application.
  • Repository: A repository interface with an implementation class to mimic CRUD operations in a Map.
  • Handler: A handler class to interact with the repository layer.
  • Server: A non-blocking Web server with single-threaded event loop. For this application, we will look how to use both Netty and Tomcat to serve requests.

The Maven POM

For web reactive programming, you need the new spring-webflux and reactive-stream modules as dependencies in your Maven POM.

To host the application in a supported runtime, you need to add its dependency. The supported runtimes are:

  • Tomcat: org.apache.tomcat.embed:tomcat-embed-core
  • Jetty: org.eclipse.jetty:jetty-server and org.eclipse.jetty:jetty-servlet
  • Reactor Netty: io.projectreactor.ipc:reactor-netty
  • Undertow: io.undertow:undertow-core

The code to add dependencies for both embedded Tomcat and Netty is this.

The final dependency is for reactive serialization and deserialization to and from JSON with Jackson.

Note – This is a pre-release of Jackson, will includes non-blocking serialization and deserialization. (Version 2.9.0 was not released at time of writing)

As we are using the latest milestone release of Spring Boot, remember to add the Spring milestones repository:

Here is the complete Maven POM.

pom.xml

The Domain Object

Our application has a Product domain object on which operations will be performed. The code for the Product object is this.

Product.java

Product is a POJO with fields representing product information. Each field has its corresponding getter and setter methods. @JsonProperty is a Jackson annotation to map external JSON properties to the Product fields.

The Repository

The repository layer of the application is built on the ProductRepository interface with methods to save a product, retrieve a product by ID, and retrieve all products.

In this example, we are mimicking the functionality of a reactive data store with a simple ConcurrentHashMap implementation.

ProductRepository.java

The important things in this interface are the new Mono and Flux reactive types of Project Reactor. Both these reactive types along with the other types of the Reactive API are capable
to serve a huge amount of requests concurrently, and to handle operations with latency. These types makes operations, such as requesting data from a remote server, more efficient. Unlike traditional processing that blocks the current thread while waiting a result, Reactive APIs are non-blocking as they deal with streams of data.

To understand Mono and Flux, let’s look at the two main interfaces of the Reactive API: Publisher, which is the source of events T in the stream and Subscriber, which is the destination for those events.

Both Mono and Fluximplements Publisher. The difference lies in cardinality, which is critical in reactive streams.

The difference lies in cardinality, which is critical in reactive streams.

  • Flux observes 0 to N items and completes either successfully or with an error.
  • A Mono observes 0 or 1 item, with Mono hinting at most 0 item.

Note: Reactive APIs were initially designed to deal with N elements, or streams of data. So Reactor initially came only with Flux. But, while working on Spring Framework 5, the team found a need to distinguish between streams of 1 or N elements, so the Mono reactive type was introduced.

Here is the repository implementation class.

ProductRepositoryInMemoryImpl.java

This ProductRepositoryInMemoryImpl class uses a Map implementation to store Product objects.

In the overridden getProduct() method, the call to Mono.justOrEmpty() creates a new Mono that emits the specified item – Product object in this case, provided the Product object is not null. For a <span class="theme:classic lang:default decode:true crayon-inline"> null value, the Mono.justOrEmpty() method completes by emitting onComplete.

In the overridden getAllProducts() method, the call to Flux.fromIterable() creates a new Flux that emits the items ( Product objects) present in the Iterable passed as parameter.

In the overridden saveProduct() method, the call to doOnNext() accepts a callback that stores the provided Product into the Map. What we have here is an example of a classic non-blocking programming. Execution control does not block and wait for the product storing operation.

The Product Handler

The Product handler is similar to a typical service layer in Spring MVC. It interacts with the repository layer. Following the SOLID Principles we would want client code to interact with this layer through an interface. So, we start with a ProductHandler interface.

The code of the ProductHandler interface is this.

ProductHandler.java

The implementation class, ProductHandlerImpl is this.

ProductHandlerImpl.java

In the getProductFromRepository(ServerRequest request) method of the ProductHandlerImpl class:

  • Line 22 obtains the product ID sent as request parameter
  • Line 23 builds a HTTP response as ServerResponse for the NOT_FOUND HTTP status.
  • Line 24 calls the repository to obtain the Product as a Mono.
  • Line 25 – Line 27: Returns a Mono that can represent either the Product or the NOT_FOUND HTTP status if the product is not found.
  • Line 31 in the saveProductToRepository(ServerRequest request) method converts the request body to a Mono. Then Line 33 calls the saveProduct() method of the repository to save the product, and finally return a success status code as an HTTP response.
  • In the getAllProductsFromRepository() method, Line 37 calls the getAllProducts() method of the repository that returns a Flux< ServerResponse>. Then Line 38 returns back the Flux as a JSON that contains all the products.

Running the Application

The example web reactive application has two components. One is the Reactive Web Server. The second is our client.

The Reactive Web Server

Now it is time to wire up all the components together for a web reactive application.

We will use embedded Tomcat as the server for the application, but will also look how to do the same with the lightweight Reactive Netty.

These we will implement in a Server class.

Server.java

In this Server class:

  • Line 37 – Line 38 creates a ProductHandler initialized with ProductRepository.
  • Line 39 – Line 43 constructs and returns a RouterFunction. In Spring Reactive Web, you can relate a RouterFunction with the @RequestMapping annotation. A RouterFunction is used for routing incoming requests to handler functions. In the Server class, incoming GET requests to /{id} and / are routed to the getProductFromRepository and getAllProductsFromRepository handler functions respectively. Incoming POST requests to / are routed to the saveProductToRepository handler function.
  • Line 53 – Line 54  in the startTomcatServer() method, integrates the RouterFunction into Tomcat as a generic HttpHandler.
  • Line 55- Line 61 initializes Tomcat with a host name, port number, context path, and a servlet mapping.
  • Line 62 finally starts Tomcat by calling the start() method.

The output on executing the Server class is this.
Output of Tomcat
To use Netty instead of Tomcat, use this code:

The Client

Spring Framework 5 adds a new reactive WebClient in addition to the existing RestTemplate. The new WebClient deserves a post on its own.

To keep this post simple and limited to only accessing our reactive Web application, I will use ExchangeFunction – a simple alternative to WebClient. ExchangeFunction represents a function that exchanges a client request for a (delayed) client response.

The code of the client class, named ReactiveClient is this.

ReactiveWebClient.java

In the ReactiveClient class, Line 21 calls the ExchangeFunctions.create() method passing a ReactorClientHttpConnector, which is an abstraction over HTTP clients to connect the client to the server. The create() method returns an ExchangeFunction.

In the createProduct() method of the ReactiveClient class, Line 30 – Line 31 builds a ClientRequest that posts a Product object to a URL represented by the URI object. Then Line 32 calls the exchange(request) method to exchange the given request for a response Mono.

In the getAllProducts() method, Line 37 starts an exchange to send a GET request to get all products.

The response body is converted into a Flux and printed to the console.

With Tomcat running, the output on running the ReactiveClient class is:
Output of Reactive Web CLient

Conclusion

In this post, I showed you a very simple example of the new web reactive features inside of Spring Framework 5.

While the reactive programming features inside of Spring Framework 5 are certainly fun to use. What, I’m finding that is, even more, fun is the functional programming style of the new Spring Framework 5 APIs.

Consider the configuration of the web reactive server:

This functional style is a significant change from what we’ve become accustomed to in Spring MVC.

Don’t worry, Spring MVC is still alive and well. And even when using the Reactive features in Spring Framework 5, you can still define ‘controllers’ in the traditional declarative sense.

And maybe traditional monolithic applications will continue to declare controllers using traditional approaches?

Where I expect the functional style to really shine is in the realm of microservices. This new functional style makes it crazy easy to define small, targeted services.

I’m looking forward to seeing how the Spring community adopts the functional API, and seeing how it evolves.

2
Share
,

If you’re following the Java community, you may be hearing about Reactive Streams in Java. Seems like in all the major tech conferences, you’re seeing presentations on Reactive Programming. Last year the buzz was all about Functional programming, this year the buzz is about Reactive Programming.

In 2016 the buzz was all about Functional programming. In 2017 the buzz is about Reactive Programming.

So, is the attention span of the Java community that short lived?

Have we Java developers forgotten about Functional programming and moved on to Reactive programming?

Not exactly. Actually, the Functional Programming paradigm complements Reactive Programming Paradigm very nicely.

You don’t need to use the Functional Programming paradigm to follow a Reactive Programming. You could use the good old imperative programming paradigm Java developers have traditionally used.  Maybe at least. You’d be creating yourself a lot headaches if you did. (Just because you can do something, does not mean you should do that something!)

Functional programming is important to Reactive Programming. But I’m not diving into Functional Programming in this post.

In this post, I want to look at the overall Reactive landscape in Java.

What is the Difference Between Reactive Programming and Reactive Streams?

With these new buzz words, it’s very easy to get confused about their meaning.

Reactive Programming is a programming paradigm. I wouldn’t call reactive programming new. It’s actually been around for awhile.

Just like object oriented programming, functional programming, or procedural programming, reactive programming is just another programming paradigm.

Reactive Streams, on the other hand, is a specification. For Java programmers, Reactive Streams is an API. Reactive Streams gives us a common API for Reactive Programming in Java.

The Reactive Streams API is the product of a collaboration between engineers from Kaazing, Netflix, Pivotal, Red Hat, Twitter, Typesafe and many others.

Reactive Streams is much like JPA or JDBC. Both are API specifications. Both of which you need use implementations of the API specification.

For example, from the JDBC specification, you have the Java DataSource interface. The Oracle JDBC implementation will provide you an implementation of the DataSource interface. Just as Microsoft’s SQL Server JDBC implementation will also provide an implementation of the DataSource interface.

Now your higher level programs can accept the DataSource object and should be able to work with the data source, and not need to worry if it was provided by Oracle or provided by Microsoft.

Just like JPA or JDBC, Reactive Streams gives us an API interface we can code to, without needing to worry about the underlying implementation.

Reactive Programming

There are plenty of opinions around what Reactive programming is. There is plenty of hype around Reactive programming too!

The best starting place to start learning about the Reactive Programming paradigm is to read the Reactive Manifesto. The Reactive Manifesto is a prescription for building modern, cloud scale architectures.

The Reactive Manifesto is a prescription for building modern, cloud scale architectures.

Reactive Manifesto

The Reactive Manifesto describes four key attributes of reactive systems:

Responsive

The system responds in a timely manner if at all possible. Responsiveness is the cornerstone of usability and utility, but more than that, responsiveness means that problems may be detected quickly and dealt with effectively. Responsive systems focus on providing rapid and consistent response times, establishing reliable upper bounds so they deliver a consistent quality of service. This consistent behaviour in turn simplifies error handling, builds end user confidence, and encourages further interaction.

Resilient

The system stays responsive in the face of failure. This applies not only to highly-available, mission critical systems — any system that is not resilient will be unresponsive after a failure. Resilience is achieved by replication, containment, isolation and delegation. Failures are contained within each component, isolating components from each other and thereby ensuring that parts of the system can fail and recover without compromising the system as a whole. Recovery of each component is delegated to another (external) component and high-availability is ensured by replication where necessary. The client of a component is not burdened with handling its failures.

Elastic

The system stays responsive under varying workload. Reactive Systems can react to changes in the input rate by increasing or decreasing the resources allocated to service these inputs. This implies designs that have no contention points or central bottlenecks, resulting in the ability to shard or replicate components and distribute inputs among them. Reactive Systems support predictive, as well as Reactive, scaling algorithms by providing relevant live performance measures. They achieve elasticity in a cost-effective way on commodity hardware and software platforms.

Message Driven

Reactive Systems rely on asynchronous message-passing to establish a boundary between components that ensures loose coupling, isolation and location transparency. This boundary also provides the means to delegate failures as messages. Employing explicit message-passing enables load management, elasticity, and flow control by shaping and monitoring the message queues in the system and applying back-pressure when necessary. Location transparent messaging as a means of communication makes it possible for the management of failure to work with the same constructs and semantics across a cluster or within a single host. Non-blocking communication allows recipients to only consume resources while active, leading to less system overhead.

The first three attributes (Responsive, Resilient, Elastic) are more related to your architecture choices. It’s easy to see why technologies such as microservices, Docker and Kubernetes are important aspects of reactive systems. Running a LAMP stack on a single server clearly does not meet the objectives of the Reactive Manifesto.

traits of reactive systemsMessage Driven and Reactive Programming

As Java developers, it’s the last attribute, Message Driven attribute, that interests us most.

Message-driven architectures are certainly nothing revolutionary. If you need a primer on message driven systems, I’d like to suggest reading Enterprise Integration Patterns. A truly iconic computer science book. The concepts in this book laid the foundations for Spring Integration and Apache Camel.

A few aspects of the Reactive Manifesto that does interest us Java developers are, failures at messages, back-pressure, and non-blocking. These are subtle, but important aspects of Reactive Programming in Java.

Failures as Messages

Often in Reactive programming, you will be processing a stream of messages. What is undesirable is to throw an exception and end the processing of the stream of messages.

The preferred approach is to gracefully handle the failure.

Maybe you needed to execute a web service and it was down. Maybe there is a backup service you can use? Or maybe retry in 10ms?

I’m not going to solve every edge case here. The key takeaway is you do not want to loudly fail with a runtime exception. Ideally, you want to note the failure, and have some type of re-try or recovery logic in place.

Often failures are handled with callbacks. Javascript developers are well accustomed to using callbacks.

But callbacks can get ugly to use. Javascript developers refer to this as call back hell.

In Reactive Steams, exceptions are first class citizens. Exceptions are not rudely thrown. Error handling is built right into the Reactive Streams API specification.

Back Pressure

Have you ever heard of the phrase “Drinking from the Firehose”?

drinking from the firehose - importance of back pressure in reactive programing.

Back Pressure is a very important concept in Reactive programming. It gives down stream clients a way to say I’d some more please.

Imagine if you’re making a query of a database, and the result set returns back 10 million rows. Traditionally, the database will vomit out all 10 million rows as fast as the client will accept them.

When the client can’t accept any more, it blocks. And the database anxiously awaits. Blocked. The threads in the chain patiently wait to be unblocked.

In a Reactive world, we want our clients empowered to say give me the first 1,000. Then we can give them 1,000 and continue about our business – until the client comes back and asks for another set of records.

This is a sharp contrast to traditional systems where the client has no say. Throttling is done by blocking threads, not programmatically.

Non-Blocking

The final, and perhaps most important, aspect of reactive architectures important to us Java developers is non-blocking.

Until Reactive came long, being non-blocking didn’t seem like that big of a deal.

As Java developers, we’ve been taught to take advantage of the powerful modern hardware by using threads. More and more cores, meant we could use more and more threads. Thus, if we needed to wait on the database or a web service to return, a different thread could utilize the CPU. This seemed to make sense to us. While our blocked thread waited on some type of I/O, a different thread could use the CPU.

So, blocking is no big deal. Right?

Well, not so much. Each thread in the system will consume resources. Each time a thread is blocked, resources are consumed. While the CPU is very efficient at servicing different threads, there is still a cost involved.

We Java developers can be an arrogant bunch.

They’ve always looked down upon Javascript. Kind of a nasty little language, preferred by script kiddies.  Just the fact Javascript shared the word ‘java’ always made us Java programmers feel a bit dirty.

If you’re a Java developer, how many times have you felt annoyed when you have to point out that Java and Javascript are two different languages?

Then Node.js came along.

And Node.js put up crazy benchmarks in throughput.

And then the Java community took notice.

Yep, the script kiddies had grown up and were encroaching on our turf.

It wasn’t that Javascript running in the Google’s V8 Javascript engine was some blazing fast godsend to programming. Java used it have its warts in terms of performance, but its pretty efficient, even compared to modern native languages.

Java used it have its warts in terms of performance, but now its pretty efficient. Even when Java compared to modern native languages.

The secret sauce of Node.js’s performance was non-blocking.

Node.js uses an event loop with limited a number of threads. While blocking in the Java world is often viewed as no big deal, in the Node.js world it would be the kiss of death to performance.

These graphics can help you visualize the difference.

In Node.JS there is a non-blocking event loop. Requests are processed in a non-blocking manner. Threads do not get stuck waiting on other processes.

node.js single thread event loop processing

Contrast the Node.JS model to the typical multithreaded server used in Java. Concurrency is achieved through the use of multiple threads. Which is generally accepted due to the growth of multi-core processors.

multi threaded server with blocking

I personally envision the difference between the two approaches as the difference between a super highway and lots of city streets with lights.

With a single thread event loop, your process is cruising quickly along on a super highway. In a Multi-threaded server, your process is stuck on city streets in stop and go traffic.

Both can move a lot of traffic. But, I’d rather be cruising at highway speeds!

your code on reactive streams

What happens when you move to a non-blocking paradigm, is your code stays on the CPU longer. There is less switching of threads. You’re removing the overhead not only managing many threads, but also the context switching between threads.

You will see more head room in system capacity for your program to utilize.

Non-blocking is a not a performance holy grail. You’re not going to see things run a ton faster.

Yes, there is a cost to managing blocking. But all things considered, it is relatively efficient.

In fact, on a moderately utilized system, I’m not sure how measurable the difference would be.

But what you can expect to see, as your system load increases, you will have additional capacity to service more requests. You will achieve greater concurrency.

How much?

Good question. Use cases are very specific. As with all benchmarks, your mileage will vary.

Learn more about my Spring Framework 5 course here!The Reactive Streams API

Let’s take a look at the Reactive Streams API for Java. The Reactive Streams API consists of just 4 interfaces.

Publisher

A publisher is a provider of a potentially unbounded number of sequenced elements, publishing them according to the demand received from its Subscribers.

Publisher

Subscriber

Will receive call to Subscriber.onSubscribe(Subscription) once after passing an instance of Subscriber to Publisher.subscribe(Subscriber).

Subscriber

Subscription

A Subscription represents a one-to-one lifecycle of a Subscriber subscribing to a Publisher.

Subscription

Processor

A Processor represents a processing stage—which is both a Subscriber and a Publisher and obeys the contracts of both.

Processor

Reactive Streams Implementations for Java

The reactive landscape in Java is evolving and maturing. David Karnok has a great blog post on Advanced Reactive Java, in which he breaks down the various reactive projects into generations. I’ll note the generations of each below – (which may change at any time with a new release).

RxJava

RxJava is the Java implementation out of the ReactiveX project.  At the time of writing, the ReactiveX project had implementations for Java, Javascript, .NET (C#), Scala, Clojure, C++, Ruby, Python, PHP, Swift and several others.

ReactiveX provides a reactive twist on the GoF Observer pattern, which is a nice approach. ReactiveX calls their approach ‘Observer Pattern Done Right’.

ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming.

RxJava predates the Reactive Streams specification. While RxJava 2.0+ does implement the Reactive Streams API specification, you’ll notice a slight difference in terminology.

David Karnok, who is a key committer on RxJava, considers RxJava a 3rd Generation reactive library.

Reactor

Reactor is a Reactive Streams compliant implementation from Pivotal. As of Reactor 3.0, Java 8 or above is a requirement.

The reactive functionality found in Spring Framework 5 is built upon Reactor 3.0.

Reactor is a 4th generation reactive library. (David Karnok is also a committer on project Reactor)

Akka Streams

Akka Streams also fully implements the Reactive Streams specification. Akka uses Actors to deal with streaming data. While Akka Streams is compliant with the Reactive Streams API specification, the Akka Streams API is completely decoupled from the Reactive Streams interfaces.

Akka Streams is considered a 3rd generation reactive library.

Ratpack

Ratpack is a set of Java libraries for building modern high-performance HTTP applications. Ratpack uses Java 8, Netty, and reactive principles. Ratpack provides a basic implementation of the Reactive Stream API, but is not designed to be a fully-featured reactive toolkit.

Optionally, you can use RxJava or Reactor with Ratpack.

Vert.x

Vert.x is an Eclipse Foundation project, which is a polyglot event driven application framework for the JVM. Reactive support in Vert.x is similar to Ratpack. Vert.x allows you to use RxJava or their native implementation of the Reactive Streams API.

Reactive Streams and JVM Releases

Reactive Streams for Java 1.8

With Java 1.8, you will find robust support for the Reactive Streams specification.

In Java 1.8 Reactive streams is not part of the Java API. However, it is available as a separate jar.

Reactive Streams Maven Dependency

While you can include this dependency directly, whatever implementation of Reactive Streams you are using, should include it automatically as a dependency.

Reactive Streams for Java 1.9

Things change a little bit when you move to Java 1.9. Reactive Streams become part of the official Java 9 API.

You’ll notice that the Reactive Streams interfaces move under the Flow class in Java 9. But other than that, the API is the same as Reactive Streams 1.0 in Java 1.8.

Conclusion

At the time of writing, Java 9 is right around the corner. In Java 9, Reactive Streams is officially part of the Java API.

In researching this article, it’s clear the various reactive libraries have been evolving and maturing (ie David Karnok generations classification).

Before Reactive Streams, the various reactive libraries had no way of interoperability. They could not talk to each other. Early versions of RxJava were not compatible with early versions of project Reactor.

But on the eve of the release of Java 9, the major reactive libraries have adopted the Reactive Streams specification. The different libraries are now interoperable.

Having the interoperability is an important domino to fall. For example, Mongo DB has implemented a Reactive Streams driver. Now, in our applications, we can use Reactor or RxJava to consume data from a Mongo DB.

We’re still early in the adaptation of Reactive Streams. But over the next year or so, we can expect more and more open source projects to offer Reactive Streams compatibilities.

I expect we are going to see a lot more of Reactive Streams in the near future.

It’s fun time to be a Java developer!

37
Share