增加数据库主备自动切换功能

This commit is contained in:
wanggeng 2021-11-29 15:43:37 +08:00
parent 6b4e43b159
commit 87a4d7270b

View File

@ -46,8 +46,7 @@ public class StandbyDataSource extends DruidDataSource implements InitializingBe
/** /**
* 备库url连接 * 备库url连接
*/ */
private String[] standbyUrls; private String standbyUrl;
private volatile int standbyIndex = 0;
@Override @Override
public void init() throws SQLException { public void init() throws SQLException {
@ -56,7 +55,7 @@ public class StandbyDataSource extends DruidDataSource implements InitializingBe
// 第一次初始化 // 第一次初始化
if (!lastInited && inited) { if (!lastInited && inited) {
// 如果没有配置不启用主备切换 // 如果没有配置不启用主备切换
if (standbyUrls == null || standbyUrls.length == 0) { if (standbyUrl == null) {
return; return;
} }
scheduledExecutorService.schedule(new ValidateUrlTask(), 1, TimeUnit.SECONDS); scheduledExecutorService.schedule(new ValidateUrlTask(), 1, TimeUnit.SECONDS);
@ -79,10 +78,8 @@ public class StandbyDataSource extends DruidDataSource implements InitializingBe
//如果这个数据源已经被初始化了,同时连接异常才进行处理 //如果这个数据源已经被初始化了,同时连接异常才进行处理
if (isInited() && !isConnectionActive()) { if (isInited() && !isConnectionActive()) {
// 主库有问题时切换备库 // 主库有问题时切换备库
LOG.debug("Change standby urls, index:{}", standbyIndex); LOG.debug("Change standby urls");
String standbyUrl = standbyUrls[standbyIndex];
changeUrl(standbyUrl); changeUrl(standbyUrl);
standbyIndex++;
break; break;
} }
try { try {
@ -105,8 +102,8 @@ public class StandbyDataSource extends DruidDataSource implements InitializingBe
setUrl(url); setUrl(url);
} }
public void setStandbyUrls(String[] standbyUrls) { public void setStandbyUrl(String standbyUrl) {
this.standbyUrls = standbyUrls; this.standbyUrl = standbyUrl;
} }
/** /**