|
|
@@ -0,0 +1,38 @@
|
|
|
+package com.fs.framework.liquibase;
|
|
|
+
|
|
|
+import org.slf4j.Logger;
|
|
|
+import org.slf4j.LoggerFactory;
|
|
|
+
|
|
|
+import javax.sql.DataSource;
|
|
|
+import java.sql.Connection;
|
|
|
+import java.sql.SQLException;
|
|
|
+import java.sql.Statement;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 校验目标数据源是否可用。
|
|
|
+ */
|
|
|
+public class DataSourceAvailabilityValidator {
|
|
|
+
|
|
|
+ private static final Logger log = LoggerFactory.getLogger(DataSourceAvailabilityValidator.class);
|
|
|
+
|
|
|
+ public void assertAvailable(DataSource dataSource, String targetName, String beanName) {
|
|
|
+ if (dataSource == null) {
|
|
|
+ throw new IllegalStateException(buildErrorMessage(targetName, beanName));
|
|
|
+ }
|
|
|
+ try (Connection connection = dataSource.getConnection()) {
|
|
|
+ if (connection.isClosed()) {
|
|
|
+ throw new IllegalStateException(buildErrorMessage(targetName, beanName));
|
|
|
+ }
|
|
|
+ try (Statement statement = connection.createStatement()) {
|
|
|
+ statement.execute("SELECT 1");
|
|
|
+ }
|
|
|
+ } catch (SQLException ex) {
|
|
|
+ log.error("Liquibase 目标 [{}] 数据源 {} 连接失败", targetName, beanName, ex);
|
|
|
+ throw new IllegalStateException(buildErrorMessage(targetName, beanName), ex);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String buildErrorMessage(String targetName, String beanName) {
|
|
|
+ return "未检测到可用数据源: target=" + targetName + ", bean=" + beanName;
|
|
|
+ }
|
|
|
+}
|