Implementation of circuit breaker in spring boot

Posted By Rupesh Sharma | 16-Sep-2018

Using microservice has its advantages but using this architecture, several things can go wrong. Sometimes while communicating among services, failure occur due to various reason like service can go down. In that case, the service calling the other one can throw an exception. So, in that case, we implement the circuit breaker to use a fallback method to be used when the other service is down. In this article, we will demonstrate circuit breaker implementation in feign client i.e when feign client fails to retrieve data from another service. Let's take an example where we are using feign client to get data from other microservice, so for that, we will create an interface for that:

@FeignClient("authentication")  
@RibbonClient("authentication")
public interface FeignClientForAuth {
	
	@RequestMapping(method=RequestMethod.GET,value="${method.path}")
	public Long getUserAddress(@RequestParam("userId") Long userId);
}

In this example, we are simply retrieving the address of a particular user by providing the userId from the authentication service. We simply provide the service id of the other service with @FeignClient and @RibbonClient call. Now we will look at the use of this interface in the implementation class.

	@HystrixCommand(fallbackMethod="fallbackMessage")
	@Override
	public Long validateOrder(Long userId) {
		JSONParser parser = new JSONParser();
		Long countryId = null;
		Long response = null;
		try {
            // using feign client to get address of the user to get the countryId.
			response = feignClientForAuth.getUserAddress(userId);
			
		} catch (FeignException e) {
			logger.error("user country fetching error:{}", e.getMessage());
			return response;
		}

         }

Now the @HystrixCommand annotation defines the circuit breaker here. Basically when the feign client will not be completed i.e the authentication is down, then, in that case, the fallback method will be called. The definition of the fallback method is:

public Long fallbackMessage(Orders orders,Long userId,String authToken) 
	{	
                // This method will be called when the authentication service is down
		return "Error.Fall back method called !"; 	
    }

 

Request for Proposal

Recaptcha is required.

Sending message..