cgf
cgf

Reputation: 3509

Is it possible to have a circuit break for the database with Spring Boot?

Having a circuit breaker with Spring Boot for external calls (e.g. HTTP) is a common pattern that is rather easy to put into place, for example with resilience4j.

I cannot find any information about doing the same with database calls, via resilience4j or some other common pattern, and this is unexpected to me.

Suppose we have a service with a simple JDBC connection to a traditional SQL database. If the database goes down for any reason, I would like to be able to stop all incoming requests to the service at the controller level until the connection is restored. Is there a way to achieve what is essentially circuit breaker functionality for all the transactions happening over the connection to the database?

Upvotes: 7

Views: 4645

Answers (1)

wmute
wmute

Reputation: 1601

Yes, this is possible. Chapter 7 of the book Spring Microservices in Action gives an example of this. Effectively, you treat a SQL call in the same way as an HTTP call:

@CircuitBreaker(name = "entityService")         ❶
public List<Entity> getEntity(String entityId) {
    return entityRepository.findByEntityId(entityId);
}

You will need the following dependencies:

io.github.resilience4j:resilience4j-spring-boot2
io.github.resilience4j:resilience4j-circuitbreaker
io.github.resilience4j:resilience4j-timelimiter
org.springframework.boot:spring-boot-starter-aop

This is using an AOP pattern of adding new behavior to existing code without modifying the code itself.

Upvotes: 4

Related Questions