Microservice Resiliency

Feign Clients

https://github.com/jeffgbutler/microservice-workshop-java/

https://jeffgbutler.github.io/microservice-workshop-java/

What is Feign?

  • Feign is a declarative REST client
  • Originated at Netflix, now in a separate orgainzation (Open Feign)
  • It is a method of calling a remote web service by defining the request and response only
  • Feign handles all the marshalling/error handling/etc. for calling a remote service
  • Spring Cloud Feign integrates Feign with the Spring web service annotations
  • Fully integrated with Eureka and Hystrix
  • Meant to be a replacement for Spring REST Template

Adding Feign to Spring Boot

  • Available in Spring Initializr as a standard dependency
  • Globally enabled with the @EnableFeignClients annotation on a configuration class

Example Feign Client

          
              @FeignClient(name="movie-award-service", url="http://localhost:8080")
              public interface MovieAwardService {
              
                  @GetMapping("/award/search")
                  List<MovieAward> findAwardsForMovie(@RequestParam("movieId") Integer movieId);
              }
          
        

This will call a web service with a URL like http://localhost:8080/award/search?movieId=3

Returned JSON will be automatically unmarshalled to the class you define

Handling 404

          
              @FeignClient(name="movie-service", decode404=true, url="http://localhost:8080")
              public interface MovieService {
                
                  @GetMapping("/movie/{id}")
                  Optional<Movie> findById(@PathVariable("id") Integer id);
              }
          
        

With decode404=true the code will return an empty Optional if there is a 404 (NOT_FOUND) error

Application Integration

  • Interfaces annotated with @FeignClient are automatically discovered and available in the Spring container
  • If you wish to share service and model definitions between a client and server:
    • Create a common interface with just the mappings and path or request valiables
    • In the server, extend the common interface and add @RestController
    • In the client, extend the common interface and add @FeignClient

Exercise

Create Feign clients in the aggregate web service