init commit
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ru.mtusi.messenger.dto.HealthDTO;
|
||||
import ru.mtusi.messenger.exception.ServiceUnavailableException;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class HealthService {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final DataSource dataSource;
|
||||
|
||||
public HealthDTO readiness() {
|
||||
requirePoolAvailable();
|
||||
requireDatabaseReachable();
|
||||
return ok();
|
||||
}
|
||||
|
||||
public HealthDTO liveness() {
|
||||
return ok();
|
||||
}
|
||||
|
||||
private void requirePoolAvailable() {
|
||||
if (dataSource instanceof HikariDataSource hikari) {
|
||||
var pool = hikari.getHikariPoolMXBean();
|
||||
if (pool != null && pool.getActiveConnections() >= hikari.getMaximumPoolSize()) {
|
||||
throw new ServiceUnavailableException("Database connection pool exhausted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void requireDatabaseReachable() {
|
||||
try {
|
||||
jdbcTemplate.queryForObject("SELECT 1", Integer.class);
|
||||
} catch (Exception e) {
|
||||
throw new ServiceUnavailableException("Database unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
private HealthDTO ok() {
|
||||
HealthDTO h = new HealthDTO();
|
||||
h.setStatus(HealthDTO.StatusEnum.OK);
|
||||
return h;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user