我是reactor的新手,我试着从Iterable创建一个flux。然后我想使用对象映射器将我的对象转换成字符串。然后,ide会在代码new ObjectMapper().writeValueAsString(event)
的这一部分中警告类似这样的消息。消息Inappropriate blocking method call
。没有编译错误。你能给我一个解决方案吗?
Flux.fromIterable(Arrays.asList(new Event(), new Event()))
.flatMap(event -> {
try {
return Mono.just(new ObjectMapper().writeValueAsString(event));
} catch (JsonProcessingException e) {
return Mono.error(e);
}
})
.subscribe(jsonStrin -> {
System.out.println("jsonStrin = " + jsonStrin);
});
发布于 2021-09-20 03:27:39
我会给你一个答案,但我不太确定这是你想要的。看起来像是阻塞了线程。因此,如果你阻塞线程,你就不能获得反应式的确切好处。这就是IDE警告您的原因。您可以使用monoSink
创建单声道。如下所示。
AtomicReference<ObjectMapper> objectMapper = new AtomicReference<>(new ObjectMapper());
Flux.fromIterable(Arrays.asList(new Event(), new Event()))
.flatMap(event -> {
return Mono.create(monoSink -> {
try {
monoSink.success(objectMapper .writeValueAsString(event));
} catch (JsonProcessingException e) {
monoSink.error(e);
}
});
})
.cast(String.class) // this cast will help you to axact data type that you want to continue the pipeline
.subscribe(jsonString -> {
System.out.println("jsonString = " + jsonString);
});
请尝试此方法,并检查错误是否会消失。
如果objectMapper
像您一样是一个普通java对象,这并不重要。(如果你不改变)。这对你的情况不是必要的。
https://stackoverflow.com/questions/69248231
复制相似问题