Skip to content

Instantly share code, notes, and snippets.

@ricston-git
Last active November 24, 2016 12:43
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ricston-git/d1696b92211a60cd9136 to your computer and use it in GitHub Desktop.
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