Spring+SpringMVC+MyBatis+MySQL 實現讀寫分離
阿新 • • 發佈:2018-11-12
簡介
主從複製實現後,主庫資料只能夠寫入資料,讀資料只能夠從庫資料完成。此時程式碼部分就需要實現讀寫分離;就需要配置多個數據源;而以前配置的DataSource 只能夠從單一的URL中獲取連線。在Spring 中提供了一個AbstractRoutingDataSource 類來可以幫我實現多個DataSource。AbstractRoutingDataSource 繼承 AbstractDataSource,而 AbstractDataSource 實現了DataSource介面。在 AbstractRoutingDataSource中提供了一個determineTargetDataSource
具體步驟如下
1. 建立類 DynamicDataSource 繼承 AbstractRoutingDataSource
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDbType();
}
}
2. 建立類 DynamicDataSourceHolder,執行緒安全管理資料來源
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DynamicDataSourceHolder {
private static Logger logger = LoggerFactory.getLogger(DynamicDataSourceHolder.class);
private static ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static final String DB_MASTET = "master";
public static final String DB_SLAVE = "slave";
/**
* @return
* @desc 獲取執行緒的dbType
*/
public static String getDbType() {
String db = contextHolder.get();
if (db == null) {
db = DB_MASTET;
}
return db;
}
/**
* @param str
* @desc 設定執行緒的dbType
*/
public static void setDbType(String str) {
logger.debug("所使用的資料來源是:" + str);
contextHolder.set(str);
}
/**
* 清理連線型別
*/
public static void clearDBType() {
contextHolder.remove();
}
}
3. 建立自定義攔截器類 DynamicDataSourceInterceptor,實現 MyBatis 的攔截器 Interceptor
/**
* @author Administrator
* @desc 設定MyBatis 的攔截器(需要使用DataSource 路由就需要通過MyBatis 攔截器,攔截SQL 請求,根據SQL
* 型別選擇不同的資料來源) DynamicDataSourceInterceptor 攔截器寫好沒用需要在 MyBatis 配置檔案中配置方可使用
* <plugins> <plugin interceptor="DynamicDataSourceInterceptor攔截器類路徑" />
* </plugins>
*/
@Intercepts({
@Signature(type=Executor.class,method="update",args= {MappedStatement.class,Object.class}),
@Signature(type=Executor.class,method="query",args= {MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class}),
})
public class DynamicDataSourceInterceptor implements Interceptor {
Logger logger = LoggerFactory.getLogger(DynamicDataSourceInterceptor.class);
// u0020 表示空格
private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";
/*
* intercept 是決定使用那個資料來源
*/
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 判斷是不是事務。true 是有事務
boolean synchronizationActive = TransactionSynchronizationManager.isActualTransactionActive();
String lookupkey = DynamicDataSourceHolder.DB_MASTET;// 決定DataSource
// 獲取CRUD 的參述
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];
if (synchronizationActive != true) {
// 讀操作
if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
// selectKey 為自增ID 查詢主鍵(select LAST_INSERT_ID())方法,使用主庫
if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
lookupkey = DynamicDataSourceHolder.DB_MASTET;
} else {
// objects 第二個參述就是 SQL
BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
// 根據中國時區,將所有制表符,換行符替換成空格
String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("[\\t\\n\\r]", " ");
// 正則 判斷是否是insert,delete,update 開頭,是使用主庫,不是使用從庫
if (sql.matches(REGEX)) {
// 寫
lookupkey = DynamicDataSourceHolder.DB_MASTET;
} else {
// 讀
lookupkey = DynamicDataSourceHolder.DB_SLAVE;
}
}
}
} else {
// 有事務,表示非查詢
lookupkey = DynamicDataSourceHolder.DB_MASTET;
}
logger.debug("設定方法[{}] use[{}] Strategy,SqlCommanType[{}]..", ms.getId(), lookupkey,
ms.getSqlCommandType().name());
DynamicDataSourceHolder.setDbType(lookupkey);
return invocation.proceed();
}
/**
* @desc 返回代理物件
*/
@Override
public Object plugin(Object target) {
// Executor,Plugin 是MyBatis 提供的類
/*
* 當攔截的物件是 Executor 這個型別,就進行攔截,就將 intercept 包裝到 wrap 中去。如果不是就直接返回本體,不受攔截
* Executor 在MyBatis 中是用來支援一系列增刪改查操作。意識就是檢測是有有CRUD操作,有就攔截,沒有就放過
*/
if (target instanceof Executor) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
}
}
4. 在MyBatis 配置檔案中 新增自定義攔截器
<plugins>
<plugin interceptor="DynamicDataSourceInterceptor攔截器類路徑" />
</plugins>
5. 修改 Spring 核心配置檔案,建立多個數據源
<bean name="abstractDataSource" abstract="true" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 初始化連線大小 -->
<property name="initialSize" value="0" />
<!-- 連線池最大使用連線數量 -->
<property name="maxActive" value="20" />
<!-- 連線池最大空閒 -->
<property name="maxIdle" value="20" />
<!-- 連線池最小空閒 -->
<property name="minIdle" value="0" />
<!-- 獲取連線最大等待時間 -->
<property name="maxWait" value="60000" />
<property name="validationQuery" value="SELECT 1" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 開啟removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分鐘 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 關閉abanded連線時輸出錯誤日誌 -->
<property name="logAbandoned" value="true" />
<!-- 監控資料庫 -->
<property name="filters" value="mergeStat" />
</bean>
<bean id="master" parent="abstractDataSource">
<property name="url" value="${jdbc_master_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
</bean>
<bean id="slave" parent="abstractDataSource">
<property name="url" value="${jdbc_slave_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
</bean>
<!-- 配置動態資料來源[master,slave 動態資料來源中[DynamicDataSource]] -->
<bean id="dynamicDataSource" class="繼承 AbstractRoutingDataSource 類的類路徑">
<property name="targetDataSources">
<map>
<!-- value-ref 和 DataSource id 保持一致 -->
<!-- key DynamicDataSourceHolder 重定義的lookupKey 一致 -->
<entry value-ref="master" key="master" />
<entry value-ref="slave" key="slave" />
</map>
</property>
</bean>
<!-- dataSource 採用 懶載入 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
<property name="targetDataSource">
<ref bean="dynamicDataSource" />
</property>
</bean>
可以通過引入 DBProxy 中介軟體,在程式和資料庫之間實現讀寫分離