聊聊reactive streams的schedulers

本文主要研究一下reactive streams的schedulers

背景

默认情况下Mono以及Flux都在主线程上运行,有时候可能会阻塞主线程,可以通过设定schedulers让其在其他线程运行。

原始输出

没有使用publishOn及subscribeOn时输出如下

11:26:10.668 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
11:26:11.097 [main] INFO com.example.demo.SchedulerTest - defer thread:[main]
11:26:11.116 [main] INFO com.example.demo.SchedulerTest - filter thread:[main]
11:26:11.116 [main] INFO com.example.demo.SchedulerTest - filter thread:[main]
11:26:11.116 [main] INFO com.example.demo.SchedulerTest - subscribe thread:[main],data :2
11:26:11.116 [main] INFO com.example.demo.SchedulerTest - filter thread:[main]
11:26:11.116 [main] INFO com.example.demo.SchedulerTest - filter thread:[main]
11:26:11.117 [main] INFO com.example.demo.SchedulerTest - subscribe thread:[main],data :4

publishOn(给subscriber配置线程)

    @Test
    public void testPublisherThread(){
        Scheduler pubScheduler = Schedulers.newSingle("pub-thread");
        Flux.defer(() -> {
            LOGGER.info("defer thread:[{}]",Thread.currentThread().getName());
            return Flux.range(1,4);
        })
                .filter(e -> {
                    LOGGER.info("filter thread:[{}]",Thread.currentThread().getName());
                    return e % 2 == 0;
                })
                .publishOn(pubScheduler)
                .subscribe(e -> {
                    LOGGER.info("subscribe thread:[{}],data :{}",Thread.currentThread().getName(),e);
                });
    }

输出

11:31:23.691 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
11:31:23.871 [main] INFO com.example.demo.SchedulerTest - defer thread:[main]
11:31:23.880 [main] INFO com.example.demo.SchedulerTest - filter thread:[main]
11:31:23.881 [main] INFO com.example.demo.SchedulerTest - filter thread:[main]
11:31:23.881 [main] INFO com.example.demo.SchedulerTest - filter thread:[main]
11:31:23.881 [main] INFO com.example.demo.SchedulerTest - filter thread:[main]
11:31:23.881 [publisher-thread-1] INFO com.example.demo.SchedulerTest - subscribe thread:[publisher-thread-1],data :2
11:31:23.881 [publisher-thread-1] INFO com.example.demo.SchedulerTest - subscribe thread:[publisher-thread-1],data :4

可以发现,配置publishOn,改变了subscribe的运行线程

subscribeOn(给publisher配置线程)

    @Test
    public void testSubscriberThread() throws InterruptedException {
        Scheduler subScheduler = Schedulers.newSingle("sub-thread");
        Flux.defer(() -> {
            LOGGER.info("defer thread:[{}]",Thread.currentThread().getName());
            return Flux.range(1,4);
        })
                .filter(e -> {
                    LOGGER.info("filter thread:[{}]",Thread.currentThread().getName());
                    return e % 2 == 0;
                })
                .subscribeOn(subScheduler)
                .subscribe(e -> {
                    LOGGER.info("subscribe thread:[{}],data :{}",Thread.currentThread().getName(),e);
                });
        Thread.sleep(10*1000);
    }

输出如下:

11:31:58.294 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
11:31:58.528 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - defer thread:[subscriber-thread-1]
11:31:58.532 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[subscriber-thread-1]
11:31:58.532 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[subscriber-thread-1]
11:31:58.532 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - subscribe thread:[subscriber-thread-1],data :2
11:31:58.533 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[subscriber-thread-1]
11:31:58.533 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[subscriber-thread-1]
11:31:58.533 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - subscribe thread:[subscriber-thread-1],data :4

可以发现,配置了subscribeOn,所有的都在这个线程运行,包括defer、包括filter、包括subscribe

publishOn和subscribeOn

    @Test
    public void testPublisherAndSubscriberThread() throws InterruptedException {
        Scheduler pubScheduler = Schedulers.newSingle("publisher-thread");
        Scheduler subScheduler = Schedulers.newSingle("subscriber-thread");
        Flux.defer(() -> {
            LOGGER.info("defer thread:[{}]",Thread.currentThread().getName());
            return Flux.range(1,4);
        })
                .filter(e -> {
                    LOGGER.info("filter thread:[{}]",Thread.currentThread().getName());
                    return e % 2 == 0;
                })
                .publishOn(pubScheduler)
                .subscribeOn(subScheduler)
                .subscribe(e -> {
                    LOGGER.info("subscribe thread:[{}],data :{}",Thread.currentThread().getName(),e);
                });
        Thread.sleep(10*1000);
    }

输出

11:33:00.964 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
11:33:01.125 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - defer thread:[subscriber-thread-1]
11:33:01.134 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[subscriber-thread-1]
11:33:01.135 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[subscriber-thread-1]
11:33:01.135 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[subscriber-thread-1]
11:33:01.135 [subscriber-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[subscriber-thread-1]
11:33:01.135 [publisher-thread-2] INFO com.example.demo.SchedulerTest - subscribe thread:[publisher-thread-2],data :2
11:33:01.135 [publisher-thread-2] INFO com.example.demo.SchedulerTest - subscribe thread:[publisher-thread-2],data :4

都配置了话,可以看到subscriber运行在publishOn配置的线程,而defer、filter等运行在subscribeOn配置的线程

publishOn及filter

    @Test
    public void testFilterThread(){
        Scheduler pubScheduler = Schedulers.newSingle("publisher-thread");
        Flux.defer(() -> {
            LOGGER.info("defer thread:[{}]",Thread.currentThread().getName());
            return Flux.range(1,4);
        })
                .publishOn(pubScheduler) //NOTE 注意这里放到了filter之前
                .filter(e -> {
                    LOGGER.info("filter thread:[{}]",Thread.currentThread().getName());
                    return e % 2 == 0;
                })
                .subscribe(e -> {
                    LOGGER.info("subscribe thread:[{}],data :{}",Thread.currentThread().getName(),e);
                });
    }

输出

13:19:01.606 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
13:19:01.754 [main] INFO com.example.demo.SchedulerTest - defer thread:[main]
13:19:01.766 [publisher-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[publisher-thread-1]
13:19:01.766 [publisher-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[publisher-thread-1]
13:19:01.766 [publisher-thread-1] INFO com.example.demo.SchedulerTest - subscribe thread:[publisher-thread-1],data :2
13:19:01.766 [publisher-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[publisher-thread-1]
13:19:01.766 [publisher-thread-1] INFO com.example.demo.SchedulerTest - filter thread:[publisher-thread-1]
13:19:01.767 [publisher-thread-1] INFO com.example.demo.SchedulerTest - subscribe thread:[publisher-thread-1],data :4

这里将publishOn放在了filter之前,可以发现filter线程也变成publisher线程了
在publishOn之后的filter或map等将使用publishOn配置的线程;之前的话,使用的是main线程或subscribeOn配置的线程

subscribeOn及filter

将subscribeOn放在filter之前,跟之后没有区别,因为没有配置publishOn时,subscribeOn作用于所有,包括filter

window scheduler

还可以给window方法设定线程池

    @Test
    public void testWindowScheduler() throws InterruptedException {
        Scheduler windowScheduler = Schedulers.newSingle("window-thread");
        Flux.defer(() -> {
            LOGGER.info("defer thread:[{}]",Thread.currentThread().getName());
            return Flux.range(1,4);
        })
                .delayElements(Duration.ofMillis(200)) //默认会创建parallel线程,作用于subscribe线程
                .windowTimeout(1, Duration.ofMillis(100), windowScheduler)
                .onErrorReturn(Flux.<Integer>just(-1))
                .flatMap(e -> {
                    return e.map(item -> item*10);
                })
                .subscribe(e -> {
                    LOGGER.info("subscribe thread:[{}],data :{}",Thread.currentThread().getName(),e);
                });
        Thread.sleep(10*1000);
    }

输出

14:15:28.523 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
14:15:28.701 [main] INFO com.example.demo.SchedulerTest - defer thread:[main]
14:15:28.961 [parallel-1] INFO com.example.demo.SchedulerTest - subscribe thread:[parallel-1],data :10
14:15:29.167 [window-thread-1] INFO com.example.demo.SchedulerTest - subscribe thread:[window-thread-1],data :20
14:15:29.370 [window-thread-1] INFO com.example.demo.SchedulerTest - subscribe thread:[window-thread-1],data :30
14:15:29.573 [parallel-4] INFO com.example.demo.SchedulerTest - subscribe thread:[parallel-4],data :40

注意delayElements方法默认给subscriber创建了parallel线程
timeout(),skip()等方法也默认会创建线程

scheduleGroup

前面在publishOn以及subscribeOn使用的都是Schedulers.newSingle,也可以使用多个线程组成的group,比如

Scheduler parallelGroup = Schedulers.newParallel("parallel-group", 8);

也可以使用elastic类型,比较适合IO类型的操作

    /**
     * {@link Scheduler} that dynamically creates ExecutorService-based Workers and caches
     * the thread pools, reusing them once the Workers have been shut down.
     * <p>
     * The maximum number of created thread pools is unbounded.
     * <p>
     * The default time-to-live for unused thread pools is 60 seconds, use the appropriate
     * factory to push a different value.
     * <p>
     * This scheduler is not restartable.
     *
     * @param name Thread prefix
     *
     * @return a new {@link Scheduler} that hosts a fixed pool of single-threaded
     * ExecutorService-based workers and is suited for parallel work
     */
    public static Scheduler newElastic(String name) {
        return newElastic(name, ElasticScheduler.DEFAULT_TTL_SECONDS);
    }

实例

    @Test
    public void testElasticGroup() throws InterruptedException {
        Scheduler elastic = Schedulers.newElastic("elastic-group");
        Flux.defer(() -> {
            LOGGER.info("defer thread:[{}]",Thread.currentThread().getName());
            return Flux.range(1,4);
        })
                .filter(e -> {
                    LOGGER.info("filter thread:[{}]",Thread.currentThread().getName());
                    return e % 2 == 0;
                })
                .publishOn(elastic)
                .map(e -> {
                    LOGGER.info("map thread:[{}]",Thread.currentThread().getName());
                    return e * 10;
                })
                .subscribeOn(elastic)
                .subscribe(e -> {
                    LOGGER.info("subscribe thread:[{}],data :{}",Thread.currentThread().getName(),e);
                });
        Thread.sleep(10*1000);
    }

输出

13:58:37.356 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
13:58:37.514 [elastic-group-2] INFO com.example.demo.SchedulerTest - defer thread:[elastic-group-2]
13:58:37.520 [elastic-group-2] INFO com.example.demo.SchedulerTest - filter thread:[elastic-group-2]
13:58:37.520 [elastic-group-2] INFO com.example.demo.SchedulerTest - filter thread:[elastic-group-2]
13:58:37.520 [elastic-group-2] INFO com.example.demo.SchedulerTest - filter thread:[elastic-group-2]
13:58:37.520 [elastic-group-2] INFO com.example.demo.SchedulerTest - filter thread:[elastic-group-2]
13:58:37.520 [elastic-group-3] INFO com.example.demo.SchedulerTest - map thread:[elastic-group-3]
13:58:37.520 [elastic-group-3] INFO com.example.demo.SchedulerTest - subscribe thread:[elastic-group-3],data :20
13:58:37.521 [elastic-group-3] INFO com.example.demo.SchedulerTest - map thread:[elastic-group-3]
13:58:37.521 [elastic-group-3] INFO com.example.demo.SchedulerTest - subscribe thread:[elastic-group-3],data :40

小结

  • 命名
    这个publishOn及subscribeOn方法名有点晦涩,更直白一点相当于subscriberThreadPools以及publisherThreadPools。
  • publishOn与operations的位置

在publishOn之后的filter或map等将使用publishOn配置的线程;之前的话,使用的是main线程或subscribeOn配置的线程

  • subscribeOn

在没有配置publishOn,只配置subscribeOn的话,则作用所有

  • 方法内置线程
    delayElements(),timeout(),skip()内置会使用额外的线程

doc

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

推荐阅读更多精彩内容