基于Flow.Publisher/Flow.Subscriber的观察者模式
基于Flow.Publisher/Flow.Subscriber的观察者模式
此Demo代码由三部分组成,分别是发布者、观察者、执行函数
发布者Sender实现Flow.Publisher
package design.mode.observer.pubsub;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
public class Sender implements Flow.Publisher {
private SubmissionPublisher<Object> publisher;
Sender(){
int THREAD_POOL_SIZE = 5;
ExecutorService EXECUTOR = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
publisher = new SubmissionPublisher<>(EXECUTOR,Flow.defaultBufferSize());
}
@Override
public void subscribe(Flow.Subscriber subscriber) {
getPublisher().subscribe(subscriber);
}
public SubmissionPublisher<Object> getPublisher() {
return publisher;
}
public void send(Map<String,Object> map){
System.out.println("publish send msg : "+map);
getPublisher().submit(map);
}
}
接收者Receiver实现Flow.Subscriber
package design.mode.observer.pubsub;
import java.util.Map;
import java.util.concurrent.Flow;
public class Receiver implements Flow.Subscriber<Map<String,Object>> {
private Flow.Subscription subscription;
private int REQ;
Receiver(int req){
this.REQ=req;
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription=subscription;
this.subscription.request(REQ);
}
@Override
public void onNext(Map<String,Object> item) {
subscription.request(REQ);
System.out.println(REQ + " onNext "+ item.toString());
}
@Override
public void onError(Throwable throwable) {
throwable.printStackTrace();
}
@Override
public void onComplete() {
System.out.println(REQ + " onComplete");
}
}
Main函数验证结果
package design.mode.observer.pubsub;
import java.util.Map;
public class PubsubMain {
public static void main(String[] args) {
Sender sender = new Sender();
Receiver receiver1 = new Receiver(1);
sender.subscribe(receiver1);
Receiver receiver2 = new Receiver(2);
sender.subscribe(receiver2);
for (int i = 0; i < 10; i++) {
sender.send(Map.of(i+"","这是第"+i+"条消息"));
}
}
}
publish send msg : {0=这是第0条消息}
publish send msg : {1=这是第1条消息}
publish send msg : {2=这是第2条消息}
publish send msg : {3=这是第3条消息}
publish send msg : {4=这是第4条消息}
publish send msg : {5=这是第5条消息}
publish send msg : {6=这是第6条消息}
publish send msg : {7=这是第7条消息}
publish send msg : {8=这是第8条消息}
publish send msg : {9=这是第9条消息}
1 onNext {0=这是第0条消息}
2 onNext {0=这是第0条消息}
2 onNext {1=这是第1条消息}
1 onNext {1=这是第1条消息}
2 onNext {2=这是第2条消息}
1 onNext {2=这是第2条消息}
2 onNext {3=这是第3条消息}
1 onNext {3=这是第3条消息}
2 onNext {4=这是第4条消息}
1 onNext {4=这是第4条消息}
2 onNext {5=这是第5条消息}
2 onNext {6=这是第6条消息}
1 onNext {5=这是第5条消息}
2 onNext {7=这是第7条消息}
1 onNext {6=这是第6条消息}
2 onNext {8=这是第8条消息}
1 onNext {7=这是第7条消息}
2 onNext {9=这是第9条消息}
1 onNext {8=这是第8条消息}
1 onNext {9=这是第9条消息}