0

I'm connecting MongoDB with Spring boot application, and my situation is that MongoDB goes down unexpectedly and throws connection exception, mongodb connection timeout exception and socket exception.

I'd like to capture the above exception in spring boot, and shutdown the app. I tried with @schduled from HealthIndicator which executes a simple command in DB for every 3sec and captures general exception, it works but it's not a correct approach because gives plenty of loads with multiple instances.

Unfortunately i couldn't use @controlleradvice and @exceptionhandler because don't want throwing any exception by executing query. The hitting DB with query gives loads to DB with multiple instances.

Is there any way to handle my situation?

2
  • Why do you want to shutdown your spring boot application when mongo is down? Have y0u considered using Spring Boot Actuator that will tell your clients that service is DOWN and not ready to accept the requests? Take a look at this question/answer - stackoverflow.com/questions/41803253/… Commented Sep 8, 2021 at 13:47
  • yeah but my business use case is that wants to shutdown, because it reads from Kafka. Business wants to shutdown rather stop reading from Kafka. Commented Sep 8, 2021 at 14:11

1 Answer 1

1

Rather than "shutting down" your app an alternative and perhaps better solution could be to implement circuit breaker where you can provide suitable fallback for failure of remote dependencies ( in your case mongodb connection timeout). There are already good libraries which implement this out-of-the-box and very easy to configure with Spring Boot. You can check out Hystrix, Resilience4J or Sentinel.

If you still want to proceed with your earlier approach of pinging the MongoDB then you can include Actuator in your dependencies and use MongoHealthIndicator to check the status yourself. It internally runs a query

@Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        Document result = this.mongoTemplate.executeCommand("{ buildInfo: 1 }");
        builder.up().withDetail("version", result.getString("version"));
    }

You can

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your inputs, let me check it out.
I tried the same approach but business is not ready to take up this option since plenty of hits to DB from multiple instances. It will be overload to DB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.