Reactor Official document translation (1) Reactor introduction

Source: Internet
Author: User
Tags maven central

Original address: http://projectreactor.io/docs/reference/

Reactor Introduction

Reactor is a base library for services that build real-time data flow applications, require fault tolerance and low latency to milliseconds, nanoseconds, and Picosecond.

-prefacetl;dr

What is reactor?

Let's get a general look at reactor. When you use your favorite search to tap some keywords like reactive, spring reactive, asynchronous Java or just "What's theheck is Reactor?". In short, reactor is a lightweight JVM base library that helps us build services and applications to deliver messages efficiently and asynchronously.

What is the meaning of efficiency?  when a message is passed from A to B, the GC produces little or no memory at all. When the  consumer processes the message faster than the producer generates the message, the overflow must be handled as quickly as possible.  provide a lock-free asynchronous stream whenever possible.

From past experience, we know that asynchronous programming is difficult, especially when a platform offers many options such as the JVM.

The reactor is aimed at true nonblocking in most scenarios and provides a more efficient set of APIs than the native JDK's java.util.concurrent library. Reactor also offers an optional (not recommended):

Blocking waits: such as Future.get ().

Unsafe data acquisition: such as Reentrantlock.lock ().

Exception throws: such as try. Catch ... finally

Synchronous blocking: such as syschronized

Wrapper configuration (GC pressure): For example, New Wrapper<t> (event)

Let's start with a pure executor method:

 private  executorservice threadPool = Executors.newfixedthreadpool (8); final  list<t> batches = new  arraylist<t> ( ); Callable  <T> T = new  callable<t>  () {//1  public   T run () { synchronized   (batches) {//2            T result  = Calldatabase (msg);//3 batches.add (Result);         return   result; }    }}; Future  <T> F = Threadpool.submit (T);//4t result  = F.get ()//5 

1. Assigning a callback method---may cause GC pressure.

2.Synchronization forces a check to be stopped for each thread.

3. There is a hidden danger that consumers ' consumption capacity is lower than producers ' productive capacity.

4. Use the thread pool to pass a task to the target thread--definitely stress the GC through Futuretask.

5. Block until Calldatabase () response.

From the simple example above, it is easy to see that extensibility can be severely affected.

Objects that are constantly allocated will cause the GC to stop working, especially if it takes more time to do large tasks. When a GC stops working, it will decrease the overall performance.

The queue length is unrestricted by default. The task is stacked in the database.

The background log is not a memory leak, but the side effects are annoying: you need to scan more objects while the GC is paused, the risk of losing the important bit of data, and so on.

The memory pressure generated when the classic link queue allocates nodes.

A vicious circle occurs when a request is answered using blocking mode.

Blocking mode response slows down producer efficiency. In fact, the process becomes a basic way of synchronizing because it waits for a response when more tasks need to be submitted.

Communication anomalies with the data store are passed to the producer in an unfriendly manner, separating the work through thread boundaries, which makes the fault-tolerant negotiation easier.

Complete, true non-blocking comparisons are difficult to achieve---especially in distributed systems with more fashionable names such as microservices architectures. However, reactor has no compromises, and it tries to use the best available model to make it unnecessary for developers to feel like they are writing a math paper and just a microservices (Nanservice).

Nothing is more light faster (except gossip and viral cat videos), and in some ways, latency is something that every real-world system must focus on. For this

The reactor provides a framework that can help you mitigate the side effects caused by nausea delays, using minimal overhead in your application: use some flexible structures to avoid allocation problems by pre-allocating allocation data structures at runtime at startup.
Restricts the primary messaging structure, and therefore does not cause infinite accumulation of tasks.
Use popular patterns such as reactive and event-driven architectures to provide a non-blocking, end-to-end flow that contains answers.
The latest reactive streaming standard is implemented to make the restricted structure more efficient by not sending more current capacity requests.
Using these concepts to interprocess communication provides a non-blocking IO driver to understand the control flow.

Exposing the feature API to developers helps developers organize the code in a no-side way, and also helps you determine what scenario you are thread-safe and fault-tolerant.

Project Introduction:

The project began in 2012 with a long gestation period. The reactor1.x version appeared in 2013. This version was successfully deployed to different organizations, not only open source organizations such as meltdown, but also commercial organizations such as pivotal RTI. We implemented the new "reactive flow standard" in 2014 and started the massive refactoring target of version 2.0 in April in 2015. The reactive flow standard pulls the gap between distribution mechanisms: Controlling how much data is passed by how many threads.

We also decided to readjust some of our event-driven and task-coordinating APIs to address the increasingly popular, documented reactive extensions.

Reactor is sponsored by pivotal and has two core submissions. Because pivotal is also the owner of the spring framework, many of our colleagues are also core contributors to different spring projects, So we also provide integration from reactor to spring and also support some of the important features of the spring framework, such as the Stomp proxy for the spring message module. In other words, we will not force people to use reactor to adapt to spring. We have retained a large-capacity reactive embedded tool. In fact, one of reactor's goals is to be impartial when you solve asynchronous and functional problems.

Reactor follows Apache 2.0 licensed and can be obtained via GitHub.

Usage Requirements:

Reactor requires JDK7 and above.

However, a complete functional composition expression requires JAVA8 lambdas support.

As a fallback, supports the extensions of spring clojure and groovy.

The reactor requires the JVM to support unsafe methods (such as Android not supported) to perform the most full function.

When unsafe gets unsupported, all Ringbuffer-based specific will not work.

Reactor packaged as a traditional jar form exists in the MAVEN Central Library, and you can use the tools you like to pull this dependency package.

 Architecture Overview :

Reactor Basic code is divided into sub-modules so that you can use a module alone and discard unwanted modules.

Here are some examples of using the reactor module and other hybrid reactive techniques to accomplish an asynchronous target:

    • Spring XD + reactor-net (core/stream): Uses Reactor as Sink/source IO driver.

    • Grails | Spring + reactor-stream (Core): Use Stream and promise as the background handler.

    • Spring Data + reactor-bus (Core): Production database events (save/delete/...?).

    • Spring Integrated Java DSL + Reactor Stream (Core): Microbatch messagechannel from Spring integration.

    • Rxjavareactivestreams + RxJava + reactor-core:combine rich composition with efficient asynchronous IO Processor

    • Rxjavareactivestreams + RxJava + reactor-net (core/stream): Compose input data with RxJava and gate with Async IO drivers .

REACTIVE stream

Reactive stream is a new standard, with different vendors and technical organizations including Netflix,oracle,pivotal,typesafe to support this standard. The standard is expected to be included in the JAVA9 or later version of the standard.

The goal of this standard is to provide a synchronous or asynchronous data sequence with a control flow mechanism. This standard is lightweight and the first target is the JVM. It provides 4 Java interfaces, a TCK and a series of examples. As needed, the implementation of the 4 Java interfaces is straightforward, and the connotation of this project is TCK's verification of the operation.

Figure three reactive stream entente

reactive STREAMS Interface Org.reactivestreams.Pubslisher: Data source (from Org.reactivestreams.Subscriber: The consumer of the data series ( from 0 to n data, N is arbitrary ). It receives a subscription,subscription at initialization to get how much data subscriber will process. Other callbacks that interact with other data timing signals are: next (new message) and optional Completion/error.

Org.reactivestreams.Processor: Both subscriber and publisher's component identity!

Figure IV: Reactive stream release pact

By passing subscriber, there are two ways to request data from subscriber to Publisher: Unlimited:  call only subscription request (Long.max_value) at the time of subscription  method. Restricted: When subscribing , the subscription reference is preserved and the request (long) method is called when Subscriber is ready to process the data.  Usually then, OnNext thinks the execution succeeds (for example, the subsequent commit, flush, and so on), requesting more data. It is recommended to use a linear group request. To avoid overlapping requests, such as requesting 10 or more data on each next request.

Table 1 So far, reactor direct use of the reactive stream interface and implementation

Reactive STREAMS Reactor Module Implement Description

processor

reactor-core, Reactor-stream

reactor.core.processor.*, reactor.rx.*

in the core module, provides a ringbuffer processor, in the stream module, provides an entire set of operations and broadcaster.

publisher

reactor-core, Reactor-bus, Reactor-stream, reactor-net

reactor.core.processor.*, reactor.rx.stream.*, reactor.rx.action.*, reactor.io.net.*

in the core module, the processor inherits Publisher. In the bus module, publish an unrestricted routed event, in the stream module, the stream extension inherits directly from Publisher. In the net module, Chanel inherits publisher to consume request data, and it also provides providers with flush and close callbacks.

subscriber

reactor-core, Reactor-bus, Reactor-stream, reactor-net

reactor.core.processor.*, reactor.bus.eventbus.*, reactor.rx.action.*, reactor.io.net.impl.*

in the core module, the processor inherits Subscriber. In the bus module, provides unrestricted publisher/ Subscriber ability. In the Stream module, subscribers calculates the specific callback behavior. In the net module, the IO layer of subscriber is implemented to handle write, close, and flush.

Subscription

Reactor-stream, Reactor-net

reactor.rx.subscription.*, reactor.io.net.impl.*

The stream module provides an optimized pushsubscriptions and Buffering-ready reactivesubscription. In the net module, asynchronous IO reads are implemented using custom subscription to implement back pressure.

We have been following this standard since Reactor 2 was launched and changed as the standard changed until the 1.0.0 official version was ready to be released. The standard can now be found through the MAVEN Central Library and its popular image, which you will find as a transition, dependent on the Reactor-core module.

REACTIVE extension

The reactive extension, or often called Rx, is a well-defined feature API that extends the observer pattern to an epic degree.

Rx Mode support enables the use of a few design keywords to process reactive data sequences:

Use a callback chain to abstract real-time and latency: Called when data can be obtained.

Abstract the thread pattern that has been used: synchronous or asynchronous is just the observable/stream we deal with.

Control error delivery and stop: the error and the completion signal and the payload signal of the data are passed into the chain.

Multiple extensions-aggregation and other combinatorial issues are addressed in a number of pre-defined APIs.

The standard JVM implementation of the reactive extension is Rxjava. It provides a feature-rich API.

Reactor 2 provides a specific module that implements a subset of the reactive extension functionality. It is recommended to use Rxjava for users who need to use reactive stream full functionality. Finally, when a complete Rxjava system is assembled, the user can benefit from the powerful asynchronous and IO provided by the reactor.

Table 2:rx and reactor stream different points:

Rx Reactor-stream Description

Observable

Reactor.rx.Stream

Reactive STREAM Publisher's implementation

Operator

Reactor.rx.action.Action

Implementation of Reactive STREAM processor

Observable with 1 data at the most

Reactor.rx.Promise

Returns the type of a unique result, reactive Stream processor implements and provides optional asynchronous distribution capabilities.

Factory API (just, from, merge ...?)

Reactor.rx.Streams

Like the data-focused subclass of the core module, the Stream is returned

Functional API (map, filter, take ...?)

Reactor.rx.Stream

Like the data-focused subclass of the core module, the stream is returned

Schedulers

Reactor.core.Dispatcher, Org.reactivestreams.Processor

Reactor Stream calculates an unrestricted shared dispatcher or limited processor operation.

Observable.observeon ()

Stream.dispatchon ()

Just an adaptation of the dispatcher parameter name.

Reactor Official document translation (1) Reactor introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.