Intro

In a previous blog post we had a look at how to use jasypt-spring-boot to encrypt our properties. Having a bit of time on my hands, I added some code to the project’s repo up on Github which we’ll be going through today. To get the complete code at the end of this post, checkout the blogpost2 branch.

The idea was to detect when we are no longer connected to our database and send ourselves an email when this happens.

In order to do this, we’ll be making use of Spring Boot’s spring-boot-actuator module and Spring’s task scheduling features.

Enabling actuators

Enabling actuators in Spring Boot is simply a matter of adding a dependency:

We now have a bunch of endpoints we can access which gives us useful information about our system, a good summary of which can be found over at Baeldung’s.

For example, if you hit the /health endpoint with our app running: http://localhost:8080/health, you should get back something like this:

That’s great, but we won’t be using the endpoints directly in this case. We can just get the bean we’re interested in from Spring’s application context, org.springframework.boot.actuate.health.DataSourceHealthIndicator.

Enabling email

The first thing we’ll need to do is add some dependencies:

Next up, we can add a JavaMailSender bean to our App.java to set up something to send emails with:

You’ll notice we’re getting some values from a properties file. You’ll want to add your own Gmail username/password (or change settings to use some other provider) in src/main/resources/config/application.properties. Of course, you can use the same method we used in Encrypting properties in Spring Boot with jasypt-spring-boot to encrypt the email password, for example.

Scheduling a task with Spring

Using Spring’s task scheduling guide, we can proceed to simply add @EnableScheduling to our App and create a new ScheduledTasks component as shown below:

Every 7 seconds (as specified in @Scheduled) we’re getting a DataSourceHealthIndicator from our Spring application context and determining whether the connection to our data source is still active. If it isn’t, we’re simply checking that we haven’t already handled this situation (by logging and sending an email), and handling it. If it is, we’re resetting the emailSent flag so that next time we lose our database connection we can handle it again.

You can try this out by switching your MySQL server on and off while the app is running with the following:

  • mysql.server start
  • mysql.server stop

Thanks for reading šŸ™‚