A quick guide on how to manually setup a fully featured Feign client in Spring Cloud
If for whatever reason you need to manually wire up a Feign client that plays nicely with Eureka, Hystrix and Ribbon in Spring Cloud it’s pretty simple and can be done in just a few steps:
Step one: Import the Feign auto-configuration class
@Configuration @Import(FeignClientsConfiguration.class) public class FeignClientConfig { ... }
Step two: Configure your feign client
@Bean public SomeService someService(Client client, Encoder encoder, Decoder decoder) { return HystrixFeign.builder() .client(client) .encoder(encoder) .decoder(decoder) .contract(new SpringMvcContract()) .target(SomeService.class, "http://some-service"); }
Step three: Profit
If you want, you can customise it even further. For example: If you want to use Feign-style annotations instead of the Spring MVC style annotations. This can cause some confusion if you use tools like swagger-io codegen to generate Feign clients. By default Spring will expect Feign client interfaces to use Spring MVC controller style annotations. You can change that by explicitly setting the contract as shown in both snippets.
@Bean public SomeService someService(Client feignClient) throws IOException { ApiClient apiClient = new ApiClient(); // generated client ObjectMapper objectMapper = apiClient.getObjectMapper(); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // add more customisations here return HystrixFeign.builder() .client(feignClient) .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) .decoder(new JacksonDecoder(objectMapper)) .contract(new Contract.Default()) .target(SomeService.class, "http://some-service"); // generated interface }
Useful links:
Maven plugin for model and client code generation from swagger definitions: https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen-maven-plugin