【问题标题】:Reactive REST API pagination反应式 REST API 分页
【发布时间】:2020-01-17 08:06:03
【问题描述】:

面临向响应式 REST API 添加分页的问题。认为有一种方法可以将 Pageable/PageRequest 字段添加到我的请求查询对象,但它不能以您将页面/大小定义为查询参数的方式工作。

只有一种可行的方法 - 将页面和大小明确定义为请求查询对象的单独字段,然后使用 PageRequest.of() 将其转换为 Pageable 对象。

问题:当它在 Spring MVC 中使用 Pageable 对象作为查询参数时,我们是否有非显式的方式向响应式 REST API 端点添加分页?

控制器:

...
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

@RestController
@RequestMapping("/foos")
@RequiredArgsConstructor
public class FooController {

    private final FooService fooService;

    @GetMapping
    @Validated
    public Mono<Page<Foo>> readCollection(FooCollectionQuery query) { // Also tried to define Pageable as separate parameter here, still not working
        return fooService.readCollection(query);
    }

}

请求查询对象:

...
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

@Value
@EqualsAndHashCode(callSuper = false)
public class FooCollectionQuery {

    @NotNull
    UUID id;

    ...

    // Pageable page; - not working
    // Page page; - not working
    // PageRequest page; - not working

}

我尝试使用分页调用端点的方式:

http://.../foos?page=1&size=2

【问题讨论】:

    标签: spring-boot spring-webflux


    【解决方案1】:

    问题解决了,由于 Spring WebFlux 不支持分页,我添加了自定义解析器 - ReactivePageableHandlerMethodArgumentResolver。

    这是我如何配置它的示例:

    @Configuration
    public class WebConfig extends WebFluxConfigurationSupport {
    
        @Override
        protected void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
            configurer.addCustomResolver(new ReactivePageableHandlerMethodArgumentResolver());
            super.configureArgumentResolvers(configurer);
        }
    
    }
    

    然后我可以在请求查询对象中使用可分页对象:

    @GetMapping
        @Validated
        public Mono<Page<Foo>> readCollection(FooCollectionQuery query, Pageable page) {
            return fooService.readCollection(query);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-13
      • 2020-11-07
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 2019-11-25
      相关资源
      最近更新 更多