Search code examples
javaspring-bootspring-cloud-feignfeign

Spring RestAPI with Feign Client and Pageable


I have a working API with all the CRUD methods i need, but i also have a Feign Client, that is throwing me and exception when my pageable GET method is called. I have tried changing it to List<>, but in the end i need it to remain Pageable, i got no clue at this point about what´s going on.

This is the working controller on the original API:

@RestController
@RequestMapping("/cargos")
public class CargoController {


    @Autowired
    private CargoService cargoService;

    // ACHAR TODOS
    @GetMapping
    public Page<Cargo> consultar(Pageable paginacao) {
        return cargoService.consultar(paginacao);

    }

}

This is the Service on the original API:

@Service
public class CargoService {
    @Autowired
    private CargoRepositorio repositoryCargos;

    // BUSCA TODOS
    public Page<Cargo> consultar(Pageable paginacao) {
        return repositoryCargos.findAll(paginacao);

    }
}

That´s all working, but in the Feign Client, every time the get method is called, it throws and exception:

catch (InvocationTargetException ex) { ReflectionUtils.rethrowRuntimeException(ex.getTargetException());

Here is how my feign client is, i got a service for it:

@FeignClient(url="http://localhost:8080/cargos",name="cargo")
public interface CargoFeign {

    //BUSCA TODOS
    @GetMapping
    Page<Cargo> consultar(Pageable paginacao);

And the Scheduler:

@Component
@Slf4j
public class CargoScheduler {

    @Autowired
    private CargoFeign cargoFeign;

    @Scheduled(cron = "0/1  * * * * *")
    public void executar() {
        log.debug("executando");

// BUSCANDO TODOS OS CARGOS
        Pageable paginacao = PageRequest.of(0, 10, Sort.by( Order.asc("id")));
        Page<Cargo> cargo2 = cargoFeign.consultar(paginacao);
        System.out.println("Listando Cargos");
        System.out.println(cargo2);
}

Solution

  • You can use Resource or Resources provided by spring HATEOAS. you need to add spring HATEOAS dependency on your client side :

    compile('org.springframework.boot:spring-boot-starter-hateoas')
    

    Enable Spring Boot’s Hypermedia Support in your main class:

    @EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
    

    and change your feign client:

    @FeignClient(url="http://localhost:8080/cargos",name="cargo")
    public interface CargoFeign {
    //BUSCA TODOS
    @GetMapping
    Resources<Cargo> consultar(Pageable paginacao);