在 Feign Client 中不支持 Spring Data Pageable 作为 RequestParam

标签 spring spring-data spring-cloud spring-cloud-feign feign

我一直在尝试为我的 rest api 公开一个 Feign Client。它接受 Pageable 作为输入并定义了 PageDefaults。

Controller :

@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 )。但是,我不确定上述情况是否未涵盖或我遗漏了某些内容。

最佳答案

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

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

客户:

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

Controller :

@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: Cannot construct instance of org.springframework.data.domain.Page



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

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

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

关于在 Feign Client 中不支持 Spring Data Pageable 作为 RequestParam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56021307/

相关文章:

spring-boot - 使用 Zuul 代理服务器时出现 "Gateway Timeout"错误

java - 为什么Spring的<jdbc :embedded-database> throw a SQLSyntaxErrorException?

带有 Spring 缓存和咖啡因的 Spring 云网关

spring-data - Spring Boot Rest 搜索 404

java - EnableSpringDataWebSupport 似乎不适用于 WebMvcConfigurerAdapter

spring-data - Liquibase:无法解析持久性单元根 URL

spring - 使用另一个类的静态方法创建 bean

java - Jackson2ObjectMapperBuilder 启用任何字段可见性

spring - 创建名为 'org.springframework.cloud.netflix.eureka.server.EurekaServerInitializerConfiguration' 的 bean 时出错

java - Spring Cloud Zuul CircuitBreaker 所有路由均通过 TurbineStream 而不是 Turbine-AMQP