Spring WebFlux 没有流式响应

标签 spring flux spring-webflux project-reactor reactive

我期待这段代码将事件流式传输到客户端(代码在 Kotlin 中,但 Java 非常相似)

@RestController
object CustomerController {
    @GetMapping("/load", produces = arrayOf("application/stream+json"))
    fun load(): Flux<String> {
        var flux = Flux.fromIterable(ResultIterable())
        flux.subscribe({println(it)})
        return flux
    }
}

ResultIterable 是一个迭代器,它定期生成一个字符串。基本上是无限流。

我没有看到任何输出,它永远挂起。

我确实看到定期打印字符串 (println(it))。

我正在使用以下 curl :

curl -X GET   http://localhost:8080/load   -H 'accept: application/stream+json'   -H 'cache-control: no-cache'   -H 'content-type: application/stream+json'

最佳答案

你的错误在这里:

flux.subscribe({println(it)})

您订阅 Flux 并直接在方法中使用它。 当这个 Flux 到达 Reactor Netty HTTP 容器时,已经没有什么可以消费了。

如果您真的想要 println() 每个项目,请考虑使用 doOnNext() 并真正将 subscribe() 留给容器。

您还必须真正遵守服务器端事件规则:

The server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream".

https://www.w3schools.com/html/html5_serversentevents.asp

所以,当我这样做时:

@GetMapping("/load", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
fun load() =
        Flux.just("foo", "bar", "baz")
                .doOnNext({ println(it) })

我开始在连接的客户端中获取服务器端事件:

C:\tmp\so50823339>curl -X GET   http://localhost:8080/load
data:foo

data:bar

data:baz


C:\tmp\so50823339>

同时我在服务器上获取提到的 doOnNext() 的日志:

2018-06-12 17:33:37.453  INFO 6800 --- [           main] c.e.s.s.So50823339ApplicationKt          : Started So50823339ApplicationKt in 3.112 seconds (JVM running for 3.924)
foo
bar
baz

关于Spring WebFlux 没有流式响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50822600/

相关文章:

spring - Kotlin 编译器返回 : Unresolved reference: springframework in Spring 5. 0

java - 如何在Spring App中显示目录?

javascript - 如何在flux中创建通用组件?

javascript - 在更深的容器组件中访问单个 Redux 商店的最佳实现是什么?

javascript - 如何使用 Flux Store 更改对象值?

java - 带有 Webflux 的 JDBC - 如何分派(dispatch)到容器线程

java - Spring webflux 中的缓存

spring - 使用 Spring Boot 序列化为对象的 Java 8 日期时间类型

Spring Boot @Autowired 自定义 application.properties

java - 为什么 spring webflux 默认选择 jetty 然后失败?