首页 > 解决方案 > Feign Client 中的 RequestParam 不支持 Spring Data Pageable

问题描述

我一直在尝试为我的 rest api 公开一个 Feign 客户端。它将 Pageable 作为输入并定义了 PageDefaults。

控制器:

@GetMapping(value = "data", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get Data", nickname = "getData")
public Page<Data> getData(@PageableDefault(size = 10, page = 0) Pageable page,
            @RequestParam(value = "search", required = false) String search) {
    return service.getData(search, page);
}

这是我的假客户:

@RequestMapping(method = RequestMethod.GET, value = "data")
public Page<Data> getData(@RequestParam(name = "pageable", required = false) Pageable page,
            @RequestParam(name = "search", defaultValue = "null", required = false) String search);

现在的问题是无论我发送给 Feign Client 的页面大小和页码如何,它总是应用 PageDefaults (0,10)。

当我直接调用其余服务时,它可以工作: http://localhost:8080/data?size=30&page=6

我正在使用 Spring Boot 2.1.4.RELEASE 和 Spring Cloud Greenwich.SR1。最近进行了修复以支持 Pageable ( https://github.com/spring-cloud/spring-cloud-openfeign/issues/26#issuecomment-483689346 )。但是,我不确定是否没有涵盖上述情况,或者我遗漏了一些东西。

标签: springspring-dataspring-cloudspring-cloud-feignfeign

解决方案


我认为您的代码不起作用,因为您在 Feign 方法中使用@RequestParam了参数注释。Pageable

我对这种方法的实现按预期工作。

客户:

@FeignClient(name = "model-service", url = "http://localhost:8080/")
public interface ModelClient {
    @GetMapping("/models")
    Page<Model> getAll(@RequestParam(value = "text", required = false) String text, Pageable page);
}

控制器:

@GetMapping("/models")
Page<Model> getAll(@RequestParam(value = "text", required = false, defaultValue = "text") String text, Pageable pageable) {
    return modelRepo.getAllByTextStartingWith(text, pageable);
}

请注意,在我的例子中,没有暴露PageJacksonModule为 bean,Spring 引发了异常:

InvalidDefinitionException:无法构造实例org.springframework.data.domain.Page

所以我不得不将它添加到项目中:

@Bean
public Module pageJacksonModule() {
    return new PageJacksonModule();
}

我的工作演示:github.com/Cepr0/sb-feign-client-with-pageable-demo


推荐阅读