Spring Reactor 项目核心库

简介: Reactor CoreNon-Blocking Reactive Streams Foundation for the JVM both implementing a Reactive Extensions inspired API and efficient event streaming support.

Reactor Core

Non-Blocking Reactive Streams Foundation for the JVM both implementing a Reactive Extensions inspired API and efficient event streaming support.

Getting it

Reactor 3 requires Java 8 or + to run.

With Gradle from repo.spring.io or Maven Central repositories (stable releases only):

    repositories {
//      maven { url 'http://repo.spring.io/snapshot' }
      maven { url 'http://repo.spring.io/milestone' }
      mavenCentral()
    }

    dependencies {
      //compile "io.projectreactor:reactor-core:3.1.4.RELEASE"
      //testCompile("io.projectreactor:reactor-test:3.1.4.RELEASE")
      compile "io.projectreactor:reactor-core:3.2.0.M1"
      testCompile("io.projectreactor:reactor-test:3.2.0.M1")
    }

See the reference documentation
for more information on getting it (eg. using Maven, or on how to get milestones and snapshots).

Note about Android support: Reactor 3 doesn't officially support nor target Android.
However it should work fine with Android SDK 26 (Android O) and above. See the
complete note
in the reference guide.

Getting Started

New to Reactive Programming or bored of reading already ? Try the Introduction to Reactor Core hands-on !

If you are familiar with RxJava or if you want to check more detailled introduction, be sure to check
https://www.infoq.com/articles/reactor-by-example !

Flux

A Reactive Streams Publisher with basic flow operators.

  • Static factories on Flux allow for source generation from arbitrary callbacks types.
  • Instance methods allows operational building, materialized on each Flux#subscribe(), Flux#subscribe() or multicasting operations such as Flux#publish and Flux#publishNext.

<img src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.3.RELEASE/src/docs/marble/flux.png" width="500">

Flux in action :

Flux.fromIterable(getSomeLongList())
    .mergeWith(Flux.interval(100))
    .doOnNext(serviceA::someObserver)
    .map(d -> d * 2)
    .take(3)
    .onErrorResumeWith(errorHandler::fallback)
    .doAfterTerminate(serviceM::incrementTerminate)
    .subscribe(System.out::println);

Mono

A Reactive Streams Publisher constrained to ZERO or ONE element with appropriate operators.

  • Static factories on Mono allow for deterministic zero or one sequence generation from arbitrary callbacks types.
  • Instance methods allows operational building, materialized on each Mono#subscribe() or Mono#get() eventually called.

<img src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.3.RELEASE/src/docs/marble/mono.png" width="500">

Mono in action :

Mono.fromCallable(System::currentTimeMillis)
    .flatMap(time -> Mono.first(serviceA.findRecent(time), serviceB.findRecent(time)))
    .timeout(Duration.ofSeconds(3), errorHandler::fallback)
    .doOnSuccess(r -> serviceM.incrementSuccess())
    .subscribe(System.out::println);

Blocking Mono result :

Tuple2<Long, Long> nowAndLater = 
        Mono.zip(
                Mono.just(System.currentTimeMillis()),
                Flux.just(1).delay(1).map(i -> System.currentTimeMillis()))
            .block();

Schedulers

Reactor uses a Scheduler as a
contract for arbitrary task execution. It provides some guarantees required by Reactive
Streams flows like FIFO execution.

You can use or create efficient schedulers
to jump thread on the producing flows (subscribeOn) or receiving flows (publishOn):


Mono.fromCallable( () -> System.currentTimeMillis() )
    .repeat()
    .publishOn(Schedulers.single())
    .log("foo.bar")
    .flatMap(time ->
        Mono.fromCallable(() -> { Thread.sleep(1000); return time; })
            .subscribeOn(Schedulers.parallel())
    , 8) //maxConcurrency 8
    .subscribe();

ParallelFlux

ParallelFlux can starve your CPU's from any sequence whose work can be subdivided in concurrent
tasks. Turn back into a Flux with ParallelFlux#sequential(), an unordered join or
use abitrary merge strategies via 'groups()'.

Mono.fromCallable( () -> System.currentTimeMillis() )
    .repeat()
    .parallel(8) //parallelism
    .runOn(Schedulers.parallel())
    .doOnNext( d -> System.out.println("I'm on thread "+Thread.currentThread()) )
    .subscribe()

Custom sources : Flux.create and FluxSink, Mono.create and MonoSink

To bridge a Subscriber or Processor into an outside context that is taking care of
producing non concurrently, use Flux#create, Mono#create.

Flux.create(sink -> {
         ActionListener al = e -> {
            sink.next(textField.getText());
         };

         // without cancellation support:
         button.addActionListener(al);

         // with cancellation support:
         sink.onCancel(() -> {
            button.removeListener(al);
         });
    },
    // Overflow (backpressure) handling, default is BUFFER
    FluxSink.OverflowStrategy.LATEST)
    .timeout(3)
    .doOnComplete(() -> System.out.println("completed!"))
    .subscribe(System.out::println)

The Backpressure Thing

Most of this cool stuff uses bounded ring buffer implementation under the hood to mitigate signal processing difference between producers and consumers. Now, the operators and processors or any standard reactive stream component working on the sequence will be instructed to flow in when these buffers have free room AND only then. This means that we make sure we both have a deterministic capacity model (bounded buffer) and we never block (request more data on write capacity). Yup, it's not rocket science after all, the boring part is already being worked by us in collaboration with Reactive Streams Commons on going research effort.

What's more in it ?

"Operator Fusion" (flow optimizers), health state observers, helpers to build custom reactive components, bounded queue generator, hash-wheel timer, converters from/to Java 9 Flow, Publisher and Java 8 CompletableFuture. The repository contains a reactor-test project with test features like the StepVerifier.


Reference Guide

http://projectreactor.io/docs/core/release/reference/docs/index.html

Javadoc

https://projectreactor.io/docs/core/release/api/

Getting started with Flux and Mono

https://github.com/reactor/lite-rx-api-hands-on

Reactor By Example

https://www.infoq.com/articles/reactor-by-example

Head-First Spring & Reactor

https://github.com/reactor/head-first-reactive-with-spring-and-reactor/

Beyond Reactor Core

  • Everything to jump outside the JVM with the non-blocking drivers from Reactor Netty.
  • Reactor Addons provide for adapters and extra operators for Reactor 3.

Powered by Reactive Streams Commons

Licensed under Apache Software License 2.0

Sponsored by Pivotal

相关文章
|
1月前
|
Java Spring
【编程笔记】在 Spring 项目中使用 RestTemplate 发送网络请求
【编程笔记】在 Spring 项目中使用 RestTemplate 发送网络请求
94 0
|
2月前
|
缓存 NoSQL Java
Spring Boot项目中热点场景详解(万字总结)
Spring Boot项目中热点场景详解(万字总结)
|
3月前
|
监控 安全 Java
Java(spring cloud)智慧工地(项目层+工地层+APP)源码
智慧工地提供工地智能管理服务,打通数据壁垒,互通管理中心各平台。实现:“可视”、“可控”、“可管”。智慧工地管理云平台是一种利用人工智能和物联网技术来监测和管理建筑工地的系统。它可以通过感知设备、数据处理和分析、智能控制等技术手段,实现对工地施工、设备状态、人员安全等方面的实时监控和管理。
31 1
|
3月前
|
Java 测试技术 Maven
Spring Boot项目打包配置详解
Spring Boot项目打包配置详解
81 0
|
4月前
|
Java Maven Spring
【Spring】Maven项目的创建
【Spring】Maven项目的创建
|
3月前
|
Java Spring 容器
springcloud项目中指定扫描路径
springcloud项目中指定扫描路径
57 7
|
30天前
|
SpringCloudAlibaba Java 持续交付
【构建一套Spring Cloud项目的大概步骤】&【Springcloud Alibaba微服务分布式架构学习资料】
【构建一套Spring Cloud项目的大概步骤】&【Springcloud Alibaba微服务分布式架构学习资料】
130 0
|
2月前
|
监控 IDE Java
Java项目调试实战:如何高效调试Spring Boot项目中的GET请求,并通过equalsIgnoreCase()解决大小写不一致问题
Java项目调试实战:如何高效调试Spring Boot项目中的GET请求,并通过equalsIgnoreCase()解决大小写不一致问题
40 0
|
3月前
|
前端开发 安全 Java
Spring Boot项目中VO层设计:选择继承或组合的灵活实践
Spring Boot项目中VO层设计:选择继承或组合的灵活实践
92 0
|
4月前
|
存储 Java Maven
如何创建Spring项目以及如何使用?
如何创建Spring项目以及如何使用?