How to do it...

  1. 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:
dependencies { 
    ... 
    compile("org.springframework.cloud:
spring-cloud-starter-consul-all") compile("org.springframework.cloud:
spring-cloud-starter-openfeign") compile("org.springframework.cloud:
spring-cloud-starter-eureka-client") compile("org.springframework.cloud:
spring-cloud-starter-netflix-hystrix") runtime("com.h2database:h2") runtime("mysql:mysql-connector-java") ... }
  1. 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 {...}
  1. 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(); 
} 
... 
  1. 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:
  • In Author.java, make the following change:
@OneToMany(mappedBy = "author", fetch = FetchType.EAGER) 
private List<Book> books; 
  • In Book.java, make the following change:
@ManyToOne(fetch = FetchType.EAGER) 
private Author author; 
 
@ManyToOne(fetch = FetchType.EAGER) 
private Publisher publisher; 
 
@ManyToMany(fetch = FetchType.EAGER) 
private List<Reviewer> reviewers; 
  • In Publisher.java, make the following change:
@OneToMany(mappedBy = "publisher", fetch = FetchType.EAGER) 
private List<Book> books; 
  1. Finally, we are ready to restart our application by executing the ./gradlew clean bootRun command.
  1. When the application has started, let's open http://localhost:8080/books in the browser and we should see an empty JSON list as a result:
..................Content has been hidden....................

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