Reactive-Stream是由Java9提供的响应式流。
具体的标准和规范有
- 处理无线数量的元素
- 有序
- 在组件之间异步传递
- 强制性非阻塞背压模式
什么是背压模式:
对应正压模式,正压模式指的是生产者对消费者的压力。背压指的是消费者对生产者的压力。
Reactive类似于,在各个系统通信的时候,运用了Kafka、mq进行消息传输,只不过是在本地进行自己的异步操作
其中包括
- 订阅者
- 发布者
- 订阅关系
- 数据处理器 (类似于Stream流的filter等操作,既是一个订阅者,又是一个发布者)
public class FlowDemo {
// 定义中间操作
static class MyProcessor extends SubmissionPublisher<String> implements Flow.Processor<String, String>{
private Flow.Subscription subscription;
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
System.out.println("》》》》》》onSubscribe");
subscription.request(1);
}
@Override
public void onNext(String item) {
System.out.println("》》》》》》onNext: " + item);
item += "蛤蛤";
submit(item);
subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
}
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(10);
// 发布者
SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
// 订阅者
Flow.Subscriber<String> subscriber = new Flow.Subscriber<>() {
private Flow.Subscription subscription;
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
System.out.println(Thread.currentThread() +"onSubscribe");
subscription.request(1);
}
@Override
public void onNext(String item) {
System.out.println(Thread.currentThread() + "onNext: " + item);
countDownLatch.countDown();
subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
System.out.println(Thread.currentThread() +"onError");
}
@Override
public void onComplete() {
System.out.println(Thread.currentThread() +"onComplete");
}
};
MyProcessor processor = new MyProcessor();
// 绑定发布者和订阅者
publisher.subscribe(processor);
processor.subscribe(subscriber);
for (int i = 0; i < 10; i++) {
publisher.submit("p"+i);
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
publisher.close();
}
}