【问题标题】:spring webflux - how to get all data from the database with an interval of 1 second?spring webflux - 如何以1秒的间隔从数据库中获取所有数据?
【发布时间】:2019-12-25 16:30:25
【问题描述】:

请告诉我。

我的 MongoDB 中有 4 条记录。好的。 我正在为当前任务使用 Reactive Spring。

如果我收到此请求,我将从我的数据库中获取所有数据(4 条记录):

@GetMapping(value = "/stream/positions", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Position> streamAllPositions() {
    return positionRepository.findAll();
}

我想指定 1 秒的时间间隔,我将从数据库中接收所有记录(4 秒内有 4 条记录)。 那些。我将收到来自数据库的第一条记录,一秒钟后我将收到来自数据库的第二条记录,一秒钟后我将收到来自数据库的第三条记录,再过一秒钟我将收到来自数据库的第四条记录。

我尝试根据每秒生成一次的默认值来执行此操作。它工作正常。

// Get default value every 1 second
@GetMapping(value = "/stream/persons", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Person> emitPersons() {
    return Flux.interval(Duration.ofSeconds(1))
            .map(val -> new Person( 1, Sex.MAN, "default", "default", 30, "default"));
}

但我需要从我的数据库中获取真实数据(不是一次全部,每条记录分别以 1 秒的间隔)。

告诉我,我该如何实现? 谢谢。

【问题讨论】:

    标签: spring mongodb spring-boot spring-webflux


    【解决方案1】:

    您可以使用delayElements 运算符:

    @GetMapping(value = "/stream/positions", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Position> streamAllPositions() {
        return positionRepository.findAll().delayElements(Duration.ofSeconds(1));
    }
    

    【讨论】:

    【解决方案2】:

    尝试在检索期间添加超时。

    参考:https://projectreactor.io/docs/core/release/reference/

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 2021-11-08
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      相关资源
      最近更新 更多