ajoy sinha
ajoy sinha

Reputation: 1236

How to implement resilience4j circuit breaker with database connection unavailability along with @ControllerAdvice

My Service Class Code

@Autowired
private BookRepository bookRepository;

@CircuitBreaker(name = "backendA", fallbackMethod = "fallbackB")
public List<Book> findAll() {
    List<Book> bookList = new ArrayList<Book>();
    bookList = bookRepository.findAll();
    return bookList;
}

public String fallbackB(Throwable e) {
    //e.printStackTrace();
    System.out.println(" I Am within fallback method of BookController");
    return CIRCUITBREAKER_FALLBACK;
}

Controller Advice implementation

@ControllerAdvice
public class NotificationAdvisor {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ErrorMessages handleException (final Exception ex) {
        
        System.out.println(" Exception within advice :: ");
        ex.printStackTrace();
        
        ErrorMessages errorMessage = new ErrorMessages();
        List<ErrorMessage> errorList = new ArrayList<ErrorMessage>();
         
        errorMessage.setErrorMessages(errorList);
        System.out.println(" Withing NotificationAdvisor !!"); 
        return errorMessage;
    }
}

POM dependency

<dependency>
            <groupId>io.github.resilience4j</groupId>
            <artifactId>resilience4j-spring-boot2</artifactId>
            <version>${resilience4j.version}</version>
        </dependency>

        <dependency>
            <groupId>io.github.resilience4j</groupId>
            <artifactId>resilience4j-circuitbreaker</artifactId>
            <version>1.7.1</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

Now, application is working fine, but if database is down then , Circuitbreaker fallbackMethod = "fallbackB" is not called, but it is calling handleException method directly. This is only happening for database call , For Rest Call Circuit breaker is working as expected.

Could you please let me know if I am missing anything here to implement Circuit breaker with Database unavailability.

Thanks in advance.

Upvotes: 0

Views: 152

Answers (0)

Related Questions