Spring 来自常规 WebClient 请求的反应性流数据
Spring reactive streaming data from regular WebClient request
我正在学习新的 Spring WebFlux 和响应式编程。
我想创建反应式 API 将一些数据流式传输到 Angular 客户端。
我将从不支持流的另一个(第三方)API 获取部分数据。
因此,据我所知,我需要:
- 创建 REST 流端点。
- Link 一些服务。
- 此服务将使用 WebClient 每 5 秒调用第三方 API。和
将数据放入我的流中。 (不确定这一步)
- 该流将由@RestController 返回。
如何实现这 4 个步骤?
假设您的远程服务响应 Jackson 可以反序列化为 Something.class
的 POJO 集合,您可以这样做:
@GetMapping(path = "/streaming", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public Flux<Something> streamSomething() {
return WebClient.create()
.get().uri("http://example.org/resource")
.retrieve().bodyToFlux(Something.class)
.delaySubscription(Duration.ofSeconds(5))
.repeat();
}
我正在学习新的 Spring WebFlux 和响应式编程。
我想创建反应式 API 将一些数据流式传输到 Angular 客户端。 我将从不支持流的另一个(第三方)API 获取部分数据。
因此,据我所知,我需要:
- 创建 REST 流端点。
- Link 一些服务。
- 此服务将使用 WebClient 每 5 秒调用第三方 API。和 将数据放入我的流中。 (不确定这一步)
- 该流将由@RestController 返回。
如何实现这 4 个步骤?
假设您的远程服务响应 Jackson 可以反序列化为 Something.class
的 POJO 集合,您可以这样做:
@GetMapping(path = "/streaming", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public Flux<Something> streamSomething() {
return WebClient.create()
.get().uri("http://example.org/resource")
.retrieve().bodyToFlux(Something.class)
.delaySubscription(Duration.ofSeconds(5))
.repeat();
}