Java StreamAPI 和 Reactive Programming

一、Lambad

@FunctionalInterface
interface Calculator {
    int add(int a, int b);

    default int add(long a, int b) {
        return (int) a + b;
    }
}

public static void main(String[] args) {
    Calculator calculator = new Calculator() {
        @Override
        public int add(int a, int b) {
            return a + b;
        }
    };

    calculator = (a, b) -> {
        return a + b;
    };

    calculator = (a, b) -> a + b;

    calculator = Integer::sum;

    new Thread(() -> System.out.println("runnable")).start();
}

 

二、Function

java.util.functionhttps://blog.csdn.net/CKXGZXA/article/details/124227749

https://ruanyifeng.com/blog/2017/02/fp-tutorial.html

https://github.com/ruanyf/es6tutorial/blob/gh-pages/docs/fp.md

https://ruanyifeng.com/blog/2017/03/pointfree.html

https://ruanyifeng.com/blog/2015/04/tail-call.html

https://github.com/shfshanyue/fp-jargon-zh

// 功能函数:有入参,有出参
Function<String, Integer> function = x -> Integer.parseInt(x);
function = Integer::parseInt;
System.out.println(function.apply("function"));

// 消费者:有入参,无出参
Consumer<String> consumer = a -> System.out.println(a);
consumer = System.out::println;
consumer.accept("consumer");

// 提供者:无入参,有出参
Supplier<String> supplier = () -> "supplier";
System.out.println(supplier.get());

// 普通函数:无入参,无出参
Runnable runnable = () -> System.out.println("runnable");
new Thread(runnable).start();



// 消费者:有两个(bi)入参,无出参
BiConsumer<String, String> biConsumer = (a, b) -> System.out.println(a + b);
biConsumer.accept("biweekly", "consumer");

// 断言
Predicate<String> predicate = x -> "predicate".equals(x);
predicate = "predicate"::equals;
System.out.println(predicate.test("predicate"));
System.out.println(predicate.negate().test("predicate"));

sample

public static void main(String[] args) {
    Supplier<String> supplier = () -> "1"; // 提供者
    Predicate<String> predicate = x -> x.matches("[0-9]+"); // 断言
    Function<String, Integer> function = Integer::parseInt; // 功能函数
    Consumer<Integer> consumer = x -> { // 消费者
        if ((x & 1) == 1) System.out.println("odd number " + x);
        else System.out.println("even number " + x);
    };
    if (predicate.test(supplier.get())) { // 使用
        consumer.accept(function.apply(supplier.get()));
    } else {
        System.out.println("not number");
    }


    methon(
            () -> "1",
            x -> x.matches("[0-9]+"),
            Integer::parseInt,
            System.out::println
    );
}

static void methon(Supplier<String> supplier, Predicate<String> predicate, Function<String, Integer> function, Consumer<Integer> consumer) {
    if (predicate.test(supplier.get())) {
        consumer.accept(function.apply(supplier.get()));
    } else {
        System.out.println("not number");
    }
}

 

三、StreamAPI

数据流 -> N个中间操作 -> 一个终止操作:https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

Stream<Integer> stream = Stream.of(1, 2, 3);
stream = Stream.concat(stream, Stream.of(4, 5, 6));
Stream<Object> objectStream = Stream.builder().add(1).add(2).add(3).build();
Stream<Object> emptyStream = Stream.empty();
Stream<Integer> intStream = IntStream.rangeClosed(0, 9).boxed();
Stream<String> arrayStream = Arrays.stream(new String[]{"a", "b", "c"});

Stream.generate(Math::random).limit(10).forEach(System.out::println); // 无限流
Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);

stream = stream.parallel(); // 并发
// stream = StreamSupport.stream(Spliterators.spliterator(), true); // 自定义线程池

 

四、Reactive Stream

Flowhttps://www.reactive-streams.org & https://reactivemanifesto.org/zh-CN

public static void main(String[] args) throws InterruptedException {
    // 发布者
    // Flow.Publisher<String> publisher = new Flow.Publisher<>() {
    //     Flow.Subscriber<? super String> subscriber;
    //     @Override
    //     public void subscribe(Flow.Subscriber<? super String> subscriber) {
    //         this.subscriber = subscriber;
    //     }
    // };
    SubmissionPublisher<String> publisher = new SubmissionPublisher<>();

    // 中间处理器
    class Processor extends SubmissionPublisher<String> implements Flow.Processor<String, String> {
        Flow.Subscription subscription;
        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            this.subscription = subscription;
            subscription.request(1);
        }
        @Override
        public void onNext(String item) {
            submit(item + "p");
            subscription.request(1);
        }
        @Override
        public void onError(Throwable throwable) {
            getSubscribers().parallelStream().forEach(x -> x.onError(throwable));
        }
        @Override
        public void onComplete() {
            getSubscribers().parallelStream().forEach(Flow.Subscriber::onComplete);
        }
    }
    Flow.Processor<String, String> processor = new Processor();

    // 订阅者
    Flow.Subscriber<String> subscriber = new Flow.Subscriber<>() {
        Flow.Subscription subscription; // 订阅关系
        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            System.out.println("订阅开始");
            this.subscription = subscription;
            // subscription.request(1); // 从上游请求一个数据
            subscription.request(Long.MAX_VALUE); // 从上游请求数据
        }
        @Override
        public void onNext(String item) {
            System.out.println("订阅者接收到数据:" + item);
            // subscription.request(1); // 从上游请求一个数据
        }
        @Override
        public void onError(Throwable throwable) {
            System.out.println("订阅者接收到错误信息:" + throwable);
            // subscription.cancel(); // 取消订阅
        }
        @Override
        public void onComplete() {
            System.out.println("订阅者接收到完成信号");
        }
    };

    // 绑定发布者和订阅者
    // publisher.subscribe(subscriber);
    // 发布者绑定处理器,处理器绑定订阅者
    publisher.subscribe(processor);
    processor.subscribe(subscriber);

    for (int i = 0; i < 10; i++) { // 发布数据
        publisher.submit(String.valueOf(i));
    }
    publisher.closeExceptionally(new RuntimeException("发布错误"));
    publisher.close(); // 完成发布

    Thread.sleep(99999);

    Flow.Subscription subscription = new Flow.Subscription() {
        @Override
        public void request(long n) {
        }
        @Override
        public void cancel() {
        }
    };
}

 

五、Reactor

https://projectreactor.io

高并发:缓存、异步、队排好。高可用:分片、复制、选领导

 


https://dev.java/learn

posted @ 2019-05-17 10:27  江湖小小白  阅读(801)  评论(0编辑  收藏  举报