Reactor知识

本文主要是介绍响应式异步编程库Reactor的使用
响应式流简介

When the publisher is faster than the subscriber, the latter must have an unbounded buffer to store fast incoming items or it must drop items it cannot handle.Another solution is to use a strategy called backpressure in which the subscriber tells the publisher to slow down and hold the tems until the subscriber is ready to process more. Using backpressure may require the publisher to have an unbounded buffer if it keeps producing and storing elements for slower subscribers.The publisher may implement a bounded buffer to store a limited number of elements and may choose to drop them if its buffer is full.

What does the subscriber do when it requests items from the publisher and the items are not available?In a synchronous request, the subscriber must wait, possibly indefinitely, until items are available. If the publisher sends items to the subscriber synchronously and the subscriber processes them synchronously, the publisher must block until the data processing finishes. The solution is to have an asynchronous processing at both ends, where the subscriber may keep working on other tasks after requesting items from the publisher. When more items are ready, the publisher sends them to the subscriber asynchronously.

Reactive Streams started in 2013 as an initiative for providing a standard for asynchronous stream processing with non-blocking backpressure. It is aimed at solving the problems of processing a stream of items—how do you pass a stream of items from a publisher to a subscriber without requiring the publisher to block or the subscriber to have an unbounded buffer or drop.

The Reactive Streams model is very simple—the subscriber sends an asynchronous request to the publisher for N items. The publisher sends N or fewer items to the subscriber asynchronously.

Reactive Streams dynamically switches between the pull model and the push model streamprocessing mechanisms. It uses the pull model when the subscriber is slower and uses the push model when the subscriber is faster.

Reactor介绍
webflux与webmvc的类比:

webmvc webflux
controller handler
request mapping router
   <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-core</artifactId>
        <version>3.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-test</artifactId>
        <version>3.1.4.RELEASE</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

一,Flue和Mono的简单用法

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


public class SimpleReactor 
{
    private static void testConstructUsingJust()
    {
        //subscribe方法中的lambda表达式作用在了每一个数据元素上
        Flux.just(1, 2, 3, 4, 5, 6).subscribe(System.out::print);
        System.out.println();//回车的作用
        Mono.just(1).subscribe(System.out::println);
    }
    
    private static void testConstructFromArray()
    {
        Integer[] array = new Integer[]{1,2,3,4,5,6};
        Flux.fromArray(array).subscribe(x -> {
            System.out.println("收到 "+ x);
            });     
    }
    
    private static void testConstructFromList()
    {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6);
        Flux<Integer> flux = Flux.fromIterable(list);   
        flux.subscribe(
                System.out::println,
                System.err::println,
                () -> System.out.println("Completed!"));
    }
    
    private static void testConstructFromStream()
    {
        Stream<Integer> stream = Arrays.asList(1,2,3,4,5,6).stream();
        Flux.fromStream(stream).subscribe(System.out::print);
    }
    
    private  static void testMonoError()
    {
        Mono.error(new Exception(" 注意注意,发生异常,注意处理啦")).subscribe(
                System.out::println,
                System.err::println,
                () -> System.out.println("Completed!")
        );
    }
    
    public static void main( String[] args )
    {
        testConstructUsingJust();
        nextTest();
        testConstructFromArray();
        nextTest();
        testConstructFromList();
        nextTest();
        testMonoError();
        nextTest();
        testConstructFromStream();
    }
    
    private static void nextTest()
    {
        System.out.println("********************************");
    }
}

二、Reactor中如何做單元測試


import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

public class SimpleReactorTest
{
    private Flux<Integer> generateFluxFrom1To6()
    {
        return Flux.just(1, 2, 3, 4, 5, 6);
    }

    private Mono<Integer> generateMonoWithError()
    {
        return Mono.error(new Exception("some error"));
    }

    @Test
    public void testViaStepVerifier()
    {
        StepVerifier.create(generateFluxFrom1To6()).expectNext(1, 2, 3, 4, 5, 6)
                .expectComplete().verify();
        StepVerifier.create(generateMonoWithError())
                .expectErrorMessage("some error").verify();
    }
}

三、Flux和Mono也支持map、flatMap、Filter、zip等operator

flatMap示意图

@Test
    public void testMapAndFlatMap()
    {
        // 注意下面的6表示6個,和IntStream的Range方法里面不一样
                StepVerifier.create(Flux.range(1, 6).map(i -> i * i))
                        .expectNext(1, 4, 9, 16, 25, 36).expectComplete();

        StepVerifier
                .create(Flux.just("flux", "mono")
                        .flatMap(s -> Flux.fromArray(s.split("\\s*"))
                                .delayElements(Duration.ofMillis(100)))
                        .doOnNext(System.out::print))
                .expectNextCount(8).verifyComplete();
    }

    @Test
    public void testFilter()
    {
        StepVerifier.create(Flux.range(1, 6).filter(i -> i % 2 == 1) // 1
                .map(i -> i * i)).expectNext(1, 9, 25) // 2
                .verifyComplete();
    }

    private Flux<String> getZipDescFlux()
    {
        String desc = "Zip two sources together, that is to say wait for all the sources to emit one element and combine these elements once into a Tuple2.";
        return Flux.fromArray(desc.split("\\s+")); // 1
    }

    @Test
    public void testZip() throws InterruptedException
    {       
        CountDownLatch countDownLatch = new CountDownLatch(1);
        //使用Flux.interval声明一个每200ms发出一个元素的long数据流;因为zip操作是一对一的,故而将其与字符串流zip之后,字符串流也将具有同样的速度;
        Flux.zip(getZipDescFlux(), Flux.interval(Duration.ofMillis(200)))
                .subscribe(
                        t -> System.out.println(t.getT1()), 
                        null,
                        countDownLatch::countDown); // 4
        countDownLatch.await(10, TimeUnit.SECONDS); // 5
    }

有些内容还没有研究完,请接着看 http://blog.51cto.com/liukang/2090191或者https://www.ibm.com/developerworks/cn/java/j-cn-with-reactor-response-encode/index.html

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,283评论 0 10
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,432评论 5 6
  • 我一直十分感慨太多人没有思想性。盲从不思考本质用英雄联盟这个游戏举个例子 上路皇子打瑞文,两人等级均为六级。瑞文血...
    皮皮鲁与鲁西西阅读 605评论 0 0
  • 温老师,如果住在赵春江工作室,请准备以下物品: 一、毛巾洗漱用品,被子还挺干净的,没有筷子,可以带点一次性筷子,最...
    浅浅淡淡唯真阅读 437评论 0 0
  • 今天的情绪失控完全在意料之外。在帮你搬箱子下去的时候还依然平静,还在跟你开着玩笑。却在关上后备箱的一刹那有点想哭...
    木木姑娘阅读 214评论 0 1