REST consumer with Hystrix and Feign

We've used Spring Framework's RestTemplate to consume microservices. Now, we are going to use Spring's Netflix Feign as a declarative REST client, instead of Spring RestTemplate, to consume microservices. We have already discussed the Spring Netflix Feign client to access REST API in Chapter 8, Simplify HTTP API with Feign Client. In this section, we will use the Feign client with the circuit-breaker pattern.

If Hystrix is on the classpath and feign.hystrix.enabled=true, Feign will wrap all methods with a circuit-breaker.

Prior to the Spring Cloud Dalston release, if Hystrix was on the classpath, Feign would have wrapped all methods in a circuit-breaker by default. This default behavior was changed in Spring Cloud Dalston in favor of an opt-in approach.

To add the Feign client in your project, add the following Maven dependency:

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

Now, let's enable fallbacks for a given @FeignClient by setting the class name to the fallback attribute of this annotation that implements the fallback. And also you have to declare your implementation as a Spring Bean. Let's see the following AccountService as a Feign client interface:

@FeignClient(name="account-service", fallback=AccountServiceFallback.class) 
public interface AccountService { 
    
   @GetMapping(value = "/account/customer/{customer}") 
   List<Account> findByCutomer (@PathVariable("customer") Integer customer); 
} 
 
class AccountServiceFallback implements AccountService { 
    @Override 
    private List<Account> findByCutomer(Integer customer) { 
         List<Account> defaultList = new ArrayList<>(); 
         defaultList.add(new Account(0000, 1.000, 0000, "UNKNOWN 
ACCOUNT TYPE", "UNK", "FALLBACK BANK")); return defaultList; }
}

The name property of the @FeignClient is mandatory. It is used to look up the application either by service discovery via a Eureka Client or via URL, if this property is given.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.189.23