我正在学习使用Java 9中的Reactive Streams并在春季使用org.reactivestreams进行反应式编程。
我正在使用webflux api spring 5和spring boot2创建一个WebClient。
现在,当我们使用webclient设置请求的主体时,我们可以在BodyInserters方法中传递一个Reactive Stream(第5版中的org.reactivestreams具体),如下所示:
WebClient.RequestHeadersSpec<?> requestSpec1 = WebClient
.create()
.method(HttpMethod.POST).uri("/getDocs")
.body(BodyInserters
.fromPublisher(Mono.just("data"),
String.class)
);
和fromPublisher方法定义:
返回一个写入给定发布者的BodyInserter。
参数: 发布者将发布者流式传输到响应主体 elementClass发布者
中包含的元素类
现在,发布者和订阅者也在java 9反应流中,我创建的一个发布者就像:
import java.util.List;
import java.util.concurrent.SubmissionPublisher;
public class TestReactiveStreams {
public static SubmissionPublisher<String> publisher;
public static void main(String...strings ) {
publisher = new SubmissionPublisher();
TestSubscriber<String> subscriber = new TestSubscriber<String>();
publisher.subscribe(subscriber);
List<String> items = List.of("1","x","2","x","3","x");
System.out.println("Subscribers = "+publisher.getNumberOfSubscribers());
if(publisher.getNumberOfSubscribers() > 0) {
items.stream().forEach(p -> publisher.submit(p));
}
publisher.close();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Consumed Elements = "+subscriber.consumed);
}
}
现在我的问题是: 是否可以在BodyInserters的fromPublisher方法中使用TestReactiveStreams中的发布者?
我尝试了以下内容:
BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter2 = BodyInserters
.fromPublisher(TestReactiveStreams.publisher, SubmissionPublisher.class);
但这会产生以下编译时错误:
The method fromPublisher(P, Class<T>) in the type BodyInserters is not applicable for the arguments
(SubmissionPublisher<String>, Class<SubmissionPublisher>)
请建议,我们如何实现这一目标?