JavaScript Required

We're sorry, but we doesn't work properly without JavaScript enabled.

Looking for an Expert Development Team? Take two weeks Trial! Try Now

Declarative Rest client using Spring Clod Feign

Techology: Spring Cloud Feign is the framework which provides way to consume Rest services on a declarative way. It provides an easier way to consume the rest services. By providing the annotations Feign framework will interact with Rest services and provides java objects by using encoders, decoders and it also httpmessage converters provided by spring web framework.

It integrates with other spring modules like Eureka server, Spring cloud Ribbon to provides service discovery and client-side load balancing automatically, without modifying the code.

Spring cloud Eureka server is service discovery applications where micro services will register with application name, so that with this name other registered micro services will consume the services without hard-coding the ipaddress of the rest service in client code.

Spring Ribbon is one of the modules which load balancer for specified applications at the client end. It will accept the comma separated urls for the same the services, so by using the algorithms it will pick one of the configured url and invoke rest service.

Maven Setup:

Create sample Spring boot web application and select Feign as dependency in http://start.spring.io or add the spring boot starter project for Feign.

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>

And any class annotated with @Configuration or @SpringBootApplicationin Spring boot application, add @EnableFeignClients annotation so that Feign framework related spring beans will be initialized.

Creating Feign Client:

@FeignClient is the annotated used to create Ribbon load balancer, if we add Spring Ribbon in class-path, this annotation accepts name/value to fetch the Service details from Eureka Server Registry if we are using Eureka Server, otherwise it is the only the name to represent the client.

If we are not using Eureka Server, then we can specify the url attribute with full absolute path of the rest service application.

The sample Feign Client will look like below:

@Component @FeignClient(name = "books", path = "/book", url = "http://localhost:8000") publicinterface BookRestClient { @RequestMapping(consumes = "application/json", produces = "application/json", method = RequestMethod.POST public Book addBook(Book book); @RequestMapping(method = RequestMethod.GET, produces = "application/json") public Iterable<Book>getAll(); @RequestMapping(consumes = "application/json", produces = "application/json", method = RequestMethod.PUT) public Book updateBook(@RequestBody Book book); @RequestMapping(produces = "application/json", method = RequestMethod.DELETE, path = "/{id}") publicvoid deleteBook(@PathVariablelong id); @RequestMapping(produces = "application/json", method = RequestMethod.GET, path = "/{id}") public Book getBook(@PathVariablelong id); }

My rest Service is running in localhost:8000/book and we specified the same in FeignCleint annotation url property, instead-of hard coding we can also externalize using application.properties.

For each requestMapping we are specifying one method, means by calling interface method, internally Feign framework call service and do the response conversion to specified return type, return the converted object. No need to write a single line of code, for contacting the rest service, by annotations also Feign framework will do everything in background.

And It is important to make sure that the annotated class must be annotated to spring stereotype of annotation, advice to annotate with Spring @Component annotation.

Customizing Feign Defaults:

Spring Cloud creates a new ensemble as an ApplicationContext on demand for each named client using FeignClientsConfiguration. This contains (amongst other things) an feign.Decoder, a feign.Encoder, and a feign.Contract.

We can also create new Configuration for each FeignClient configuration property, where we can add any new messageconverters additional to client application needed, or any decoders, encoder are needed, we can specify the CustomConfiguration class and creating beans for it.

CustomConfiguration class need to annotate with @Configuration, as it is specific to @Feign client, and if we want to share this configuration to all FeignClient then only specify the @configuration annotation. If the class is annotated with @Configuration, make sure that it is added to separate package which is not available for component-scan.

Spring Cloud Netflix provides the following beans by default for feign (beanName: ClassName):

feignDecoder: ResponseEntityDecoder feignEncoder: SpringEncoder feignLogger: Slf4jLogger feignContract: SpringMvcContract feignBuilder: HystrixFeign.Builder Client feignClient: if Ribbon is enabled it is a LoadBalancerFeignClient, otherwise the default feign client is used.

We can also customize the httpclient which library is used for contacting the rest service, by default RestTemplate is used to invoke the rest service.

But alternatively we can use OKHTTP library, by setting the feign.okhttp.enabled property to true. If we want to use apache httpclient, by setting the property feign.httpclient.enabled to true, and add the corresponding libraries to classpath.

If the rest service is secured, then we can write RequestInterceptor to intercept the request, add the authentication details into it.

For this we need to add the Configuration class and same provide to FeignClient property.

We can configure the connectionTimeout, log levels while contacting the service using below configuration, which will applicable for all FeignClients.

We can also specify configuration using spring application properties:

feign.client.config.book.decoder=com.example.SimpleDecoder feign.client.config.book.encoder=decoder=com.example.SimpleEncoder feign.client.config.book.error-decoder=com.example.SimpleErrorDecoder feign.client.config.book.connect-timeout=5000 feign.client.config.book.read-timeout=5000 feign.client.config.book.logger-level=FULL feign.client.config.book.decode404=false feign.client.config.book.request-interceptors=com.example.BookRequestInterceptor

where book is out FeignClient name, we can also specify the same set of default properties under default key, insteadof book use default, which will be shared across all FeignClients.

SpringFeign also support Circuit breaker using Hystrix library, we can create a bean which implments Feign interface and provide the implemented class as fallback. Or we can implement the HystrixClientFallbackFactory interface and return object as Feign interface, and also it should be a spring bean.

Spring Feign client applicationContext found two beans of the same interface types, if we enable Hystrix, so we need to mark the FeignClient interface as Primary property.

Feign Request/Response Compression: we can compress the Rest service request, response by setting the below properties:

feign.compression.request.enabled=true feign.compression.response.enabled=true

we can also selectively compress the requests by setting the minimum request size in application properties file.

feign.compression.request.min-request-size=2048

Conclusion:

This Blog explained how to build Rest client in declarative way, to consume Rest Services, and how to customize each client, and also default configuration properties for all Feign Clients, if the service is secured then, using Interceptors how to pass authentication details for Rest services.

Source code will be available at https://github.com/sravan4rmhyd/SpringCloudFeignExample.git

Keep Visiting Aegis Infoways Blog for More information about Microsoft Dynamics 365 and Java Development Services.