Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spring Boot "poor man's" database down email notification
@Value("${email.username}")
private String emailUsername;
@Value("${email.password}")
private String emailPassword;
@Bean
public JavaMailSender mailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(25);
mailSender.setUsername(emailUsername);
mailSender.setPassword(emailPassword);
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
mailSender.setJavaMailProperties(props);
return mailSender;
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
</dependency>
{
"status": "UP",
"diskSpace": {
"status": "UP",
"free": 263739887616,
"threshold": 10485760
},
"db": {
"status": "UP",
"database": "MySQL",
"hello": 1
}
}
@Component
public class ScheduledTasks {
private static final Logger LOG = LoggerFactory.getLogger(ScheduledTasks.class);
private static boolean emailSent = false;
@Autowired
ApplicationContext appContext;
@Autowired
JavaMailSender mailSender;
@Value("${email.to}")
private String toAddress;
@Scheduled(fixedDelay = 7000)
public void detectLostDbConnection() {
DataSourceHealthIndicator dshi = appContext.getBean(DataSourceHealthIndicator.class);
Health health = dshi.health();
Status status = health.getStatus();
if (status != null && "DOWN".equals(status.getCode())) {
if (!emailSent) {
LOG.error("Database connection lost");
try {
mailSender.send(dbConnectionLostMailMessage());
emailSent = true;
} catch (MailException ex) {
LOG.error("'Database connection lost' email notification failed");
}
}
} else {
emailSent = false;
}
}
private SimpleMailMessage dbConnectionLostMailMessage() {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setSubject("Database connection lost");
msg.setTo(toAddress);
msg.setText("Houston, we have a problem");
return msg;
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.