Reactive Spring -- 1. Reactive概念和Project Reactor

Spring 5 中引入了Reactive理念,下文主要介绍Reactive模式的基础。

工程地址分支为reactive-operations

Reactive概念

Reactive是函数式编程(Functional),管道流(pipeline, stream), 异步非阻塞的,事件驱动的。

org.reactivestreams包中主要有4个接口

  • 发布者Publisher
public interface Publisher<T> {

    public void subscribe(Subscriber<? super T> s);
    
}
  • 订阅者Subscriber

当接收到Publisher的数据时,会调用响应的回调方法。注册完成时,首先会调用onSubscribe方法,参数Subscription s包含了注册信息。

public interface Subscriber<T> {
    
    // 注册完成后,首先被调用
    public void onSubscribe(Subscription s);
    
    public void onNext(T t);
    
    public void onError(Throwable t);
    
    public void onComplete();
}
  • 订阅Subscription
  1. 通过订阅,订阅者Subscriber可以请求数据request,或者取消订阅cancel
  2. 在请求数据时,参数long n表示希望接收的数据量,防止发布者Publisher发送过多的数据。
  3. 一旦开始请求,数据就会在流stream中传输。每接收一个,就会调用onNext(T t);发生错误时,onError(Throwable t)被调用;传输完成后,onComplete()被调用。
public interface Subscription {
    
    // 请求数据,参数n为请求的数据量,不是超时时间
    public void request(long n);

    // 取消订阅
    public void cancel();
}
  • Processor

可以看出,Processor接口继承了SubscriberPublisher,是流的中间环节。

public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {

}

Reactive Stream中数据从Publisher开始,经过若干个Processor,最终到达Subcriber,即完整的Pipeline。

Project Reactor

依赖
<dependency>
  <groupId>io.projectreactor</groupId>
  <artifactId>reactor-core</artifactId>
</dependency>

MonoFlux
  1. 抽象类MonoFlux实现了Publisher接口,他们是发布者。
  2. Mono表示少于等于1个数据(即0个, 或1个数据)或错误;Flux表示一连串多个数据。
操作
  1. 创建FluxMono,调用subscribe()后,数据开始流动。

主要方法有:just, fromArray, fromStream, fromIterable, range


    @Test
    public void create() {
    
        //just方法
        String[] arr = new String[]{"hello", "world"};
        Flux<String> flux1 = Flux.just(arr);
        flux1.subscribe(System.out::println);

        Mono<String> mono = Mono.just("hi world");
        mono.subscribe(System.out::println);
        
        //fromArray方法
        List<String> list = Arrays.asList("hello", "world");
        Flux<String> flux2 = Flux.fromIterable(list);
        
        //fromIterable方法
        List<String> fruitList = new ArrayList<>();
        fruitList.add("Apple");
        fruitList.add("Orange");
        fruitList.add("Grape");
        fruitList.add("Banana");
        fruitList.add("Strawberry");
        Flux<String> flux3 = Flux.fromIterable(fruitList);
        
        //fromStream方法
        Stream<String> stream = Stream.of("hi", "hello");
        Flux<String> flux4 = Flux.fromStream(stream);
        
        //range方法
        Flux<Integer> range = Flux.range(0, 5);
        
        //interval方法, take方法限制个数为5个
        Flux<Long> longFlux = Flux.interval(Duration.ofSeconds(1)).take(5);
    }
    
    

  1. 合并mergeWith
@Test
public void mergeFlux() {
    Flux<String> source1 = Flux.just("hello", "world");
        Flux<String> source2 = Flux.just("hi", "ted");

        Flux<String> merge = source1.mergeWith(source2);
        merge.subscribe(System.out::println);
}
  1. 结合为Tuple2元组类型zipWith
@Test
public void zipFlux() {
    Flux<String> source1 = Flux.just("hello", "world");
    Flux<String> source2 = Flux.just("hi", "ted");

    Flux<Tuple2<String, String>> zip = source1.zipWith(source2);
    zip.subscribe(tuple -> {
        System.out.println(tuple.getT1() + " -> " + tuple.getT2());
    });
}
  1. 转换和过滤

skip: 略过2个


@Test
public void skipFlux() {
    Flux<String> source1 = Flux.just("hello", "world", "hi", "ted");

    Flux<String> skip = source1.skip(2);
    skip.subscribe(System.out::println);
}

take:只取前2个

@Test
public void takeFlux() {
    Flux<String> source1 = Flux.just("hello", "world", "hi", "ted");

    Flux<String> skip = source1.take(2);
    skip.subscribe(System.out::println);
}

filter: 接收Predicate

@Test
public void filterFlux() {
    Flux<String> source1 = Flux.just("hello", "world", "hi", "ted");

    Flux<String> skip = source1.filter(s -> s.startsWith("h"));
    skip.subscribe(System.out::println);
}

distinct: 去重

@Test
public void distinctFlux() {
    Flux<String> source1 = Flux.just("hello", "hello", "world", "hi", "ted");

    Flux<String> skip = source1.filter(s -> s.startsWith("h")).distinct();
    skip.subscribe(System.out::println);
}

map: 接收Function

@Test
public void mapFlux() {
    Flux<String> source1 = Flux.just("hello", "world", "hi", "ted");

    Flux<String> skip = source1.map(s -> s + " is mapped");
    skip.subscribe(System.out::println);
}

flatMap: 根据Flux中的元素先生成Mono, 再对Mono中的元素进行map转换。

@Test
public void flatMapFlux() {
    Flux<String> source1 = Flux.just("hello world", "hi ted");

    Flux<String> flatMap = source1.flatMap(s -> Mono.just(s).map(s1 -> {
        String[] strings = s1.split("\\s");
        return new String(strings[0] + " - " + strings[1]);
    }));

    flatMap.subscribe(System.out::println);
}

buffer: 将stream中的数据按照固定大小分配,新的Flux中的List的元素个数是2

@Test
public void bufferFlux() {
    Flux<String> source1 = Flux.just("hello", "world", "hi", "ted");
    Flux<List<String>> buffer = source1.buffer(2);

    buffer.subscribe(strings -> System.out.println(strings.size()));
}

collectList: 将Flux中的元素收集到一个List中

@Test
public void collectListFlux() {
    Flux<String> source1 = Flux.just("hello", "world", "hi", "ted");
    Mono<List<String>> mono = source1.collectList();
    
    mono.subscribe(System.out::println)
}

collectMap: 将Flux中的元素提取为一个Map,Map的key根据Function生成

@Test
public void collectMapFlux() {
        Flux<String> source1 = Flux.just("hello", "world", "ted");

        Mono<Map<Character, String>> map = source1.collectMap(s -> s.charAt(0));
        map.subscribe(characterStringMap -> System.out.println(characterStringMap.get('t')));
}

  1. 逻辑运算

all: 判断Flux中元素是否都满足Predicate条件

@Test
public void allFlux() {
    Flux<String> source1 = Flux.just("hello", "world", "ted");

    Mono<Boolean> mono = source1.all(s -> s.contains("e"));
    mono.subscribe(System.out::println);
}

any: 判断Flux中元素是否至少有1个满足Predicate条件

@Test
public void anyFlux() {
    Flux<String> source1 = Flux.just("hello", "world", "ted");

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

推荐阅读更多精彩内容