concept Hystrix command in category camel

appears as: Hystrix command, Hystrix commd, Hystrix commds, The Hystrix commd, Hystrix commd
Camel in Action

This is an excerpt from Manning's book Camel in Action.

You may have noticed in listing 7.14 the COUNTER instance, which is used as a global state stored outside the Hystrix command, and the fact that the example is constructed to fail every fifth call. How do you deal with exceptions thrown from the run method?

Figure 7.8  The Hystrix command uses a thread from the regular thread pool ❶ to route the Camel message. The task runs, and upon completion, the command completes successfully ❷. But the task can also fail because of a time-out or an exception thrown during Camel routing, which causes the Hystrix command to run the fallback using a thread from the fallback thread pool ❸. This ensures isolation between run and fallback, adhering to the bulkhead principle.

c07_08.png

Support for Hystrix on Spring Boot requires you to implement an @Service class, which holds the code to run as a Hystrix command. The following listing shows what you did to add fault-tolerance at number ❶ in figure 7.9.

Listing 7.16 Using Hystrix in Spring Boot as an @Service class
@Service     #1 public class ShoppingCartService { private final RestTemplate restTemplate = new RestTemplate(); @HystrixCommand(fallbackMethod = "emptyCart")     #2 public String shoppingCart(String cartUrl, String id) { CartDto[] carts = restTemplate.getForObject(cartUrl, CartDto[].class, id);     #3 String cartIds = Arrays.stream(carts) .map(CartDto::toString) .collect(Collectors.joining(","));     #4 return cartIds; } public String emptyCart(String cartUrl, String id) {     #5 return ""; } } #1 Annotates class as a Spring @service class #2 Marks method as Hystrix command #3 Calls downstream service #4 Converts response to a comma-separated String #5 Method used as Hystrix fallback

Here you create a new class, ShoppingCartService, which is responsible for calling the downstream shopping cart service. The class has been annotated with @Service ❶ (or @Component), which is required by Spring when using Hystrix. The @HystrixCommand annotation ❷ is added on the method that will be wrapped as a Hystrix command. All the code that runs inside this method will be under the control of Hystrix. Inside this method, you call the downstream service ❸ using Spring’s RestTemplate to perform a REST call. Having a response, you transform this into a comma-separated string using Java 8 stream magic ❹. The @HystrixCommand annotation specifies the name of the fallback method that refers to the emptyCart method ❺. This method does what the name says: returns an empty shopping cart as its response.