spring實現數據庫的自動切換
我們要實現的是多個數據庫之間的自動切換,因此面臨的主要問題就是:
-
數據源是否有效的檢測
-
程序中切換使用的數據庫
數據源的有效檢測方法:
單開一條線程,間斷的發送一條命令執行,如果執行成功則認爲數據庫有效,不成功則認爲該數據源無效。
數據庫的切換:
Spring提供了一個抽象類 AbstractRoutingDataSource
,實類中有一個抽象方法
protected Object determineCurrentLookupKey()
實現這個方法返回要使用的數據源的key就能夠使用對應的數據源做數據庫的操作。
因此兩個基本的問題就都解決了,接下來就是代碼實現了。
這裏省去基本的spring工程的各類配置步驟,以及數據庫的互備和數據的導入步驟。
下面示例工程使用的是spring+mybatis+druid連接池作爲數據庫操作的框架。兩個數據庫主主互備,並且將工程使用的數據已經導入數據庫中。在此基礎上編寫我們切換數據庫的代碼。
首先按照傳統的方式配置數據源,配置方式和以前spring工程配置數據源的方式相同。
如下圖所示,我使用druid配置了兩個數據源。分別是dataSourceTest1和dataSourceTest2
<bean id="dataSourceTest1" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" init-method="init"
lazy-init="true">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.test1.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="dataSourceTest2" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" init-method="init"
lazy-init="true">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.test2.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
Jdbc配置屬性如下:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.test1.url=jdbc:mysql://127.0.0.1:3307/gwpms?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=PRC&autoReconnect=true
jdbc.test2.url=jdbc:mysql://127.0.0.1:3308/gwpms?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=PRC&autoReconnect=true
jdbc.username=root
jdbc.password=123456
可以看到兩個數據源分別使用兩個不同的數據庫。
然後就是使用 AbstractRoutingDataSource 的實現類,配置一個數據源提供給程序使用。
<bean id="dataSourceTest" class="com.starnet.gwpms.web.MultipleDataSourceToChoose" lazy-init="true">
<description>數據源</description>
<property name="targetDataSources">
<map key-type="java.lang.String" value-type="javax.sql.DataSource">
<entry key="dataSourceTest1" value-ref="dataSourceTest1" />
<entry key="dataSourceTest2" value-ref="dataSourceTest2" />
</map>
</property>
<!-- 設置默認的目標數據源 -->
<property name="defaultTargetDataSource" ref="dataSourceTest1" />
</bean>
MultipleDataSourceToChoose 是我定義的AbstractRoutingDataSource 的實現類,觀察配置可以看見配置了一個*targetDataSources,*當中配置的就是我們之前配置的數據源bean。使用map key-value的方式配置。這裏的key就是我們要在determineCurrentLookupKey()方法中返回的值,返回key後,連接會切換到對應的數據源。
MultipleDataSourceToChoose 的實現如下:
package com.starnet.gwpms.web;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class MultipleDataSourceToChoose extends AbstractRoutingDataSource {
private static String dataSourceKey;
public static void setDataSourceKey(String dataSource) {
dataSourceKey = dataSource;
}
/**
* @desction: 根據Key獲取數據源的信息,上層抽象函數的鉤子
* @param:
* @return:
*/
@Override
protected Object determineCurrentLookupKey() {
return dataSourceKey;
}
}
這裏還提供了一個靜態方法設置使用的數據源。
之後再配置一個bean,同樣的把所有的數據源注入進去,方便在當中檢查數據源的有效性。
<bean id="dataSourceContextHolder" class="com.starnet.gwpms.web.DataSourceContextHolder">
<description>數據源</description>
<property name="targetDataSources">
<map key-type="java.lang.String" value-type="javax.sql.DataSource">
<entry key="dataSourceTest1" value-ref="dataSourceTest1" />
<entry key="dataSourceTest2" value-ref="dataSourceTest2" />
</map>
</property>
<!-- 設置默認的目標數據源 -->
<property name="defaultTargetDataSource" ref="dataSourceTest1" />
</bean>
DataSourceContextHolder的代碼實現。主要做了以下工作:
-
通過配置文件將所有數據源注入成員變量當中。
-
單開一條線程間斷的查詢數據庫,通過查詢結果判斷數據庫的有效性。使用的數據庫無效則切換數據庫。
代碼如下:
package com.starnet.gwpms.web;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
public class DataSourceContextHolder implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(DataSourceContextHolder.class);
//配置中注入所有的數據源
private Map<String, DataSource> targetDataSources;
private DataSource defaultTargetDataSource;
private Map<String, Boolean> validDataSources = new HashMap<String, Boolean>();
private String useDataSourceKey;
public void setTargetDataSources(Map<String, DataSource> targetDataSources) {
this.targetDataSources = targetDataSources;
}
public void setDefaultTargetDataSource(DataSource defaultTargetDataSource) {
this.defaultTargetDataSource = defaultTargetDataSource;
}
@Override
public void afterPropertiesSet() throws Exception {
for (Entry<String, DataSource> dataSource: targetDataSources.entrySet()) {
validDataSources.put(dataSource.getKey(), true);
if (defaultTargetDataSource == dataSource.getValue()) {
useDataSourceKey = dataSource.getKey();
}
}
if (useDataSourceKey == null) {
logger.error("default datasource key is null.");
}
new Thread(new DataSourceValidate(), "DATASOURCE-VALIDATE-THREAD").start();
}
//數據源有效性檢測線程,每隔1秒檢測一次
public class DataSourceValidate implements Runnable {
@Override
public void run() {
while (true) {
for (Entry<String, DataSource> dataSource: targetDataSources.entrySet()) {
if (checkDataSource(dataSource.getValue())) {
validDataSources.put(dataSource.getKey(), true);
} else {
validDataSources.put(dataSource.getKey(), false);
}
}
//如果正在使用的數據源不可用,自動切換到可用的數據源上
if (!validDataSources.get(useDataSourceKey)) {
for (Entry<String, Boolean> validDataSource: validDataSources.entrySet()) {
if (validDataSource.getValue()) {
useDataSourceKey = validDataSource.getKey();
logger.debug("change datasource, {}", useDataSourceKey);
MultipleDataSourceToChoose.setDataSourceKey(validDataSource.getKey());
break;
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.debug(e.getMessage(), e);
}
}
}
public boolean checkDataSource(DataSource ds) {
try (
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
) {
stmt.execute("select 1");
return true;
} catch (SQLException e) {
logger.debug(e.getMessage(), e);
return false;
}
}
}
}