To get started with Hystrix we need to add the spring-cloud-starter-hystrix library to our project. Let's modify our build.gradle file located in the root of our project with the following content:
After adding the Hystrix dependency, we need to enable Hystrix for our application. Similar to how we enabled service discovery, we will do that by making a change to the BookPubApplication.java file located under the src/main/java/com/example/bookpub directory from the root of our project with the following content:
...
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
public class BookPubApplication {...}
Now, let's make a few changes to BookController.java, located under the src/main/java/com/example/bookpub/controllers directory from the root of our project, with the following content:
@RequestMapping(value = "", method = RequestMethod.GET)
@HystrixCommand(fallbackMethod = "getEmptyBooksList")
public Iterable<Book> getAllBooks() {
//return bookRepository.findAll();
throw new RuntimeException("Books Service Not Available");
}
public Iterable<Book> getEmptyBooksList() {
return Collections.emptyList();
}
...
Due to Hystrix internal functionality, we also need to modify our entity models to have them eager-load the relational associations. In the Author.java, Book.java, and Publisher.java files located under the src/main/java/com/example/bookpub/entity directory from the root of our project, let's make the following changes: