Reactive Programming with Java

java

Most of the conversations about reactive programming didn’t accurately convey its meaning. In fact, reactive programming is aimed at effective resource use, asynchrony and non-blocking.

Reactive Stream API

image1

Reactive streams are asynchronous thread processing, so a publisher and a subscriber shall be required. All reactive systems are built on this principle. The publisher publishes the data stream, and the subscriber uses the data. Sometimes we have to convert data between the publisher and the subscriber. According to the chart, the Publisher publishes the data stream, and the subscriber uses the data. In the Subscription, by request, cancellation and upon request, we will receive onNext (onError / onComplete).

It depends on how successfully the action was completed. It’s important that a set is returned on onNext, then onNext will be called several times.

According to the manifest, reactive programming should contain the following architecture:

image3

As described in the reactive manifesto there are different scenarios: Responsive (responsiveness of the system), Resilient (stress resistance, in the event of a system failure we do not cause a failure at all), Elastic (dynamically reacts to load) and Message-Driven. The system should essentially provide an answer in a reasonable amount of time.

Reactivity in Java

Frameworks (Framework can be used instead of applying any third-party libraries to write the code.):

  • Akka, Play Framework
  • Spring Fu
  • Vert.x.
  • Spring WebFlux
Libraries
  • RxJava
  • Project Reactor
  • Java 9 (Flow) → (added Publisher and Subscriber interfaces)

Let’s start with Project Reactor, the first to implement this reactor paradigm in Spring. It has created a set of reactive primitives that simplify the work and work over Publisher-Subscriber and provide Fluent API. It consists of:

Micro Reactive Toolkit for all:

  • Reactor Core
  • Reactor Testing (Should assist with testing, our reactive interaction)
  • Reactor Adapter (RxJava, Akka — we can turn RxJava primitives into Project Reactor primitives.)
  • Reactor Extra (there are various additional operations on primitives there)

Spring WebFlux

  • Spring WebFlux — built on the Reactor project.
  • There are two interfaces, Mono (Single result) and Flux (Multiple results).

What Spring projects are working?

  • Spring Data Core. But note that Spring Data JPA and other blocking projects will not work.
  • Spring MVC. It supports only part of the MVC concept.
  •  Spring Security.
  • Spring Cloud.

Databases should be non-blocking database IO with WebFlux. A typical back-end looks like this:

  1. NoSQL type databases:
    •  MongoDB
    • Redis
    • CouchBase
    • Cassandra
  2. Databases of SQL type (as a rule, an enterprise solution):
    • R2DBC (H2, MS SQL, PostgreSQL)
    • R2DBC- proxy
    • RxJava- jdbc

If you briefly summarize the database should be an asynchronous driver from database developers.

this.mongoTemplate.inTransaction()
 .execute(s->Flux.just("First name", "Last name")
 .flatMap(
 name->s.insert(
 Call.bulder
 .title(name)
 .content("name - " + name)
 .build()
 )
 )
 )
 .subscribe(
 v -> log.info("One name"),
 e->log.error("Error"),
 ()->log.info("data")
 );

In the example, a transaction enables us to get a connection. We create Flux from a constant and insert it into the database. When the transaction has been done, we perform a subscription. As the first signature, we use lambda.

Server implementation should be non-blocking HTTP with WebFlux support.

Servers:

  • Netty,
  • Undertow
  • Servlet 3.1+ (Jetty, Tomcat,…)
Client:
  • Spring WebClient
  • Netty
  • Undertow
  • HTTP Client (JEP 321)
image2

Vert.x

The concept of Vert.x is to be reactive, unlike Spring. Spring rewrites its codebase with WebFlux, which has serious doubts about the realizability of this rewriting, against Vert.x.

The principle is such as EventLoop, which is spinning on Thread: some Events can wait, then something next is taken. If you have a lot of Thread, then Vert.x will be able to cluster them even outside of one machine, and to abstract you from how much Thread you have.

public class ServerVerticle extends AbstractVerticle {

 @Override
 public void start(Future<Void> startFuture) throws Exception {

 vertx.createHttpServer().requestHandler(req ->
 {
 req.response()
 .putHeader("content-type", "text/plain")
 .end("Start Vert.x");
 }).listen(8080);
 }
}

To write reactive code, Vert.x uses a Verticle that listens to requests. A request sends an event, and everything is updated asynchronously-reactively and processed. If there is a delay, then it goes to the background and the next request is processed.

I found Benchmarks showed that in fact there is no difference between Spring and Vert.x in the number of requests. The quality of resources consumed like Vert.x is very profitable. If a large load is not the number of requests, and the load on the server, this approach can save resources.

I always have a question: why?

Actually, reactive programming sounds beautiful, the concept is also good, but it has some extra complexity:

  • Complex Debug. For example, you may start on one thread and end up on another, and it may cause some difficulties.
  • The code becomes less clear because reactive programming makes it difficult. In fact, the whole application will be flashed with primitives, it is not always readable.
  • Be very attentive to dependencies if they are blocking because most of the libraries are not intended for reactive programming. Make sure that it is not blocking or not using it in or as a third option, not using it through the main thread, or limit themselves to the use of auxiliary threads.

When should I use it?

  • When you have a large service with frequent requests.
  • A huge number of simultaneous connection requests to make it really profitable and useful.

Conclusion

First of all, you should estimate the system to choose a technology stack. As in the case of reactive programming, the presence of one event blocking, reactivity will lose all sense.  Spring Reactor should be used for the project built on the Spring ecosystem, and Vert.x is preferable for the project written from scratch or Vert.x ecosystem. So, Spring Reactor and Vert.x are fast-growing technologies, and soon we will see what technology has been more viable.

Please, estimate my article. I did my best!
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 3.33 out of 5)
Loading…

Leave a Reply

Your email address will not be published. Required fields are marked *

Share
Share