Spring boot Spring WebClient错误-reactor.core.publisher.FluxOnAssembly无法转换为reactor.core.publisher.Mono类
下面是我已经实现的rest服务Spring boot Spring WebClient错误-reactor.core.publisher.FluxOnAssembly无法转换为reactor.core.publisher.Mono类,spring-boot,groovy,spring-webflux,Spring Boot,Groovy,Spring Webflux,下面是我已经实现的rest服务 @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE, value = "/events") Flux<Event> events() { Flux<Event> eventFlux = Flux.fromStream(Stream.generate {new Event(System.currentTimeMillis(), LocalDate.now())})
@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE, value = "/events")
Flux<Event> events() {
Flux<Event> eventFlux = Flux.fromStream(Stream.generate {new Event(System.currentTimeMillis(), LocalDate.now())})
Flux<Long> durationFlux = Flux.interval(Duration.ofSeconds(1))
return Flux.zip(eventFlux, durationFlux)
.map {it.t1}
}
public static void main(String[] args) {
SpringApplication.run(ReactiveServiceApplication)
}
我得到的错误如下
@Bean
WebClient client() {
return WebClient.create("http://localhost:8080")
}
@Bean
CommandLineRunner demo (WebClient client) {
return { args ->
client.get().uri("/events")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.flatMap { response -> response.bodyToFlux(Event.class) }
.subscribe { println it }
}
}
public static void main(String[] args) {
new SpringApplicationBuilder(ReactiveClientApplication)
.properties(Collections.singletonMap("server.port","8081"))
.run(args)
}
reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.ClassCastException: class reactor.core.publisher.FluxOnAssembly cannot be cast to class reactor.core.publisher.Mono (reactor.core.publisher.FluxOnAssembly and reactor.core.publisher.Mono are in unnamed module of loader 'app')
Caused by: java.lang.ClassCastException: class reactor.core.publisher.FluxOnAssembly cannot be cast to class reactor.core.publisher.Mono (reactor.core.publisher.FluxOnAssembly and reactor.core.publisher.Mono are in unnamed module of loader 'app')
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:118) ~[reactor-core-3.3.5.RELEASE.jar:3.3.5.RELEASE]
为什么会发生错误 原因是使用
flatMap
实际返回的是Mono
。因此,闭包{response->response.bodyToFlux(Event.class)}
实际上返回了Flux
,而flatMap
期望的是Mono
更改为flatMapMany
将解决此问题。代码如下
CommandLineRunner getFluxDemoExchange (WebClient client) {
return { args ->
client.get().uri("/events")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.flatMapMany { response -> response.bodyToFlux(Event.class) }
.subscribe { println it }
}
}