如何在反应性Spring数据中应用分页?

Ste*_*eph 9 reactive-programming spring-data spring-data-mongodb

在Spring Data中,我们PagingAndSortingRepository继承了它CrudRepository.在反应式Spring数据中,我们只有 ReactiveSortingRepository继承自ReactiveCrudRepository.我们怎么能以反应的方式进行分页呢?例如,我们将来能够做到这一点ReactivePagingAndSortingRepository吗?

mp9*_*1de 13

反应性Spring数据MongoDB存储库不提供分页意义上的分页,它是如何为命令性存储库设计的.在获取页面时,命令式分页需要其他详细信息.特别是:

  • 分页查询的返回记录数
  • (可选)如果返回的记录数为零或与页面大小匹配以计算总页数,则查询产生的记录总数

这两个方面都不符合高效,无阻塞资源使用的概念.等到收到所有记录(以确定第一个分页详细信息块)将消除通过响应数据访问获得的大部分好处.此外,执行计数查询相当昂贵,并且在您能够处理数据之前增加滞后.

您仍然可以通过将Pageable(PageRequest)传递给存储库查询方法来自己获取数据块:

interface ReactivePersonRepository extends Repository<Person, Long> {

  Flux<Person> findByFirstnameOrderByLastname(String firstname, Pageable pageable);
}
Run Code Online (Sandbox Code Playgroud)

Spring Data将通过转换PageableLIMIT和来对查询应用分页OFFSET.

参考文献:


kn3*_*n3l 8

import com.thepracticaldeveloper.reactiveweb.domain.Quote;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import reactor.core.publisher.Flux;

public interface QuoteMongoReactiveRepository extends ReactiveCrudRepository<Quote, String> {

    @Query("{ id: { $exists: true }}")
    Flux<Quote> retrieveAllQuotesPaged(final Pageable page);
}
Run Code Online (Sandbox Code Playgroud)

更多细节,你可以在这里查看