面对向反应式 REST API 添加分页的问题。以为有一种方法可以将Pageable/PageRequest
字段添加到我的请求查询对象中,但它无法以您将能够将页面/大小定义为查询参数的方式工作。
只有一种方法 - 将页面和大小显式定义为请求查询对象的单独字段,然后使用PageRequest.of()
将其转换为Pageable
对象。
问题:我们是否有非显式的方式来向反应式 REST API 端点添加分页,因为它在 Spring MVC 中使用对象作为查询参数Pageable
工作?
控制器:
...
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不支持分页,我添加了自定义解析器 - 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);
}