first commit
This commit is contained in:
@ -40,6 +40,7 @@ public class DatasourceConnectionMonitor {
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
// 1s钟运行一次
|
||||
new Timer().schedule(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
@ -62,6 +63,10 @@ public class DatasourceConnectionMonitor {
|
||||
if (check(connection)) {
|
||||
// 说明数据源正常
|
||||
log.trace("租户[{}]-目前主数据源正常, 无需切换数据源", tenantId);
|
||||
// 主数据 处理任务
|
||||
if (TenantConstant.DEFAULT_TENANT_ID.equals(tenantId)) {
|
||||
handleJob();
|
||||
}
|
||||
IoUtil.close(connection);
|
||||
continue;
|
||||
}
|
||||
@ -74,7 +79,7 @@ public class DatasourceConnectionMonitor {
|
||||
IoUtil.close(dataSource);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
//e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -89,7 +94,8 @@ public class DatasourceConnectionMonitor {
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
stmt = conn.createStatement();
|
||||
stmt.setQueryTimeout(1);
|
||||
// 允许 2s 延时
|
||||
stmt.setQueryTimeout(2);
|
||||
rs = stmt.executeQuery(CHECK_SQL);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
@ -129,13 +135,9 @@ public class DatasourceConnectionMonitor {
|
||||
// 切换成功
|
||||
DynamicDataSource dynamicDataSource = dataSources.get(backupIndex);
|
||||
// 更改数据库中该数据源为主要数据源
|
||||
if (!TenantConstant.DEFAULT_TENANT_ID.equals(dynamicDataSource.getTenantId())) {
|
||||
try {
|
||||
dynamicDatasourceService.changePrimaryDatasource(dynamicDataSource.getTenantId(), dynamicDataSource.getDatasourceId());
|
||||
} catch (Exception e) {
|
||||
// 说明主数据源也挂了
|
||||
WAIT_UPDATE_DATASOURCE_STATUS.put(dynamicDataSource.getTenantId(), dynamicDataSource.getDatasourceId());
|
||||
}
|
||||
if (Objects.nonNull(dynamicDataSource.getTenantId()) && !TenantConstant.DEFAULT_TENANT_ID.equals(dynamicDataSource.getTenantId())) {
|
||||
// 添加到待处理任务中
|
||||
WAIT_UPDATE_DATASOURCE_STATUS.put(dynamicDataSource.getTenantId(), dynamicDataSource.getDatasourceId());
|
||||
}
|
||||
// 备用数据源集合删除该数据源
|
||||
dataSources.remove((int) backupIndex);
|
||||
@ -146,4 +148,20 @@ public class DatasourceConnectionMonitor {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleJob() {
|
||||
Set<String> keys = WAIT_UPDATE_DATASOURCE_STATUS.keySet();
|
||||
for (String key : keys) {
|
||||
try {
|
||||
log.info("开始更新数据库中租户数据源状态, 租户ID: {}", key);
|
||||
// 防止更新过程中主数据挂了
|
||||
dynamicDatasourceService.changePrimaryDatasource(key, WAIT_UPDATE_DATASOURCE_STATUS.get(key));
|
||||
// 处理完成 删除任务
|
||||
WAIT_UPDATE_DATASOURCE_STATUS.remove(key);
|
||||
log.info("更新数据库中租户数据源状态完成, 租户ID: {}", key);
|
||||
} catch (Exception e) {
|
||||
log.error("更新数据库中租户数据源状态完成, 租户ID: {}, 失败原因: {}", key, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user