【问题标题】:Spring Reactor - consuming Pageable endpointSpring Reactor - 使用 Pageable 端点
【发布时间】:2020-05-28 05:52:59
【问题描述】:

这是我第一次使用 Spring Reactor,我面临以下挑战:

我有一项服务,它允许使用由页码和页面大小指定的许多记录:

 Mono<GetContactsForGroupResponse> getContactsForGroup(Integer page, Integer size);

GetContactsForGroupResponse 包含分页元数据的其他字段:

class GetContactsForGroupResponse {
    private int totalPages;
    private int totalElements;
    private int numberOfElements;
    private int size;
    private int number;
    private boolean first;
    private boolean last;
    //.....
}

现在我需要编写另一个方法来读取来自

的所有页面
Mono<GetContactsForGroupResponse> getContactsForGroup(Integer page, Integer size);

并将结果合并到一个集合中:

Mono<Collection<GetContactsForGroupResponse>> getContactsForGroup();

到目前为止,我已经写了:

            List<GetContactsForGroupResponse> groupContacts = new ArrayList<>();
            AtomicBoolean allPagesConsumed = new AtomicBoolean(false);

            int pageNumber = 0;
            int pageSize = 10;

            while(!allPagesConsumed.get()) {
                allPagesConsumed.set(true);
                GetContactsForGroupResponse getContactsForGroupResponse =
                        getContactsForGroup(accountId, g.getId(), 0, pageSize).block();
                Optional.ofNullable(getContactsForGroupResponse)
                        .ifPresent(r -> {
                            allPagesConsumed.set(r.isLast());
                            groupContacts.add(r);
                        });

                pageNumber ++;

我逐页阅读结果,直到读到最后一页。 我想知道从 SpringReactor 的角度来看,正确的实现方式是什么

任何建议都将不胜感激,

谢谢

【问题讨论】:

标签: spring spring-webflux spring-reactive spring-reactor spring-mono


【解决方案1】:

没有“正确的方法”,因为这不是一个被动的问题。

由于您正在获取“页面”,因此您正在处理一种非反应性的数据处理方式。您尚未透露有关如何获取此数据以及来自什么类型的数据库的任何信息。

最简单的方法是查询数据库并一次性获取所有内容。

写一个getAllContactsForGroup,而不是,做一个while循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 2018-11-22
    • 2017-01-10
    • 2019-04-04
    • 2015-03-28
    • 2019-05-17
    • 1970-01-01
    相关资源
    最近更新 更多