反应式REST API分页反应式、分页、REST、API

2023-09-04 01:37:45 作者:鹤川.

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

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

REST API自动化文档生成

问题:在使用Pageable对象作为查询参数的Spring MVC中工作时,我们是否有非显式的方式向反应式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 WebFlux不支持分页,我增加了自定义的解析器-Solver

以下是我如何配置它的示例:

@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);
    }