首先需要配置好資料庫的主從同步:
上一篇文章中有寫到:https://www.cnblogs.com/xuyiqing/p/10647133.html
為什麼要進行讀寫分離呢?
通常的Web應用大多數讀操作次數遠大于寫操作
為了提高效率,我們可以考慮讀寫分離
讀寫分離可以采用DBProxy中間件,這裡不談這種方式
而是使用Mabatis攔截器
大體思路是:
得到SQL語句進行分析,如果是select那麼配置設定從資料庫資料源
反之,配置設定主資料庫資料源
Spring重寫路由:
package org.dreamtech.o2o.dao.split;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 資料源路由重寫,用于讀寫分離
*
* @author Xu Yiqing
*
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDbType();
}
}
自定義工具類:
package org.dreamtech.o2o.dao.split;
/**
* 輔助進行讀寫分離操作
*
* @author Xu Yiqing
*
*/
public class DynamicDataSourceHolder {
private static ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static final String DB_MASTER = "master";
public static final String DB_SLAVE = "slave";
/**
* 擷取dbType
*
* @return dbType
*/
public static String getDbType() {
String db = contextHolder.get();
if (db == null) {
db = DB_MASTER;
}
return db;
}
/**
* 設定線程的dbType
*
* @param str
* 類型
*/
public static void setDbType(String str) {
contextHolder.set(str);
}
/**
* 清理連接配接類型
*/
public static void clearDBType() {
contextHolder.remove();
}
}
Mybatis過濾器:
package org.dreamtech.o2o.dao.split;
import java.util.Locale;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Mybatis攔截器,實作讀寫分離
*
* @author Xu Yiqing
*
*/
@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 {
private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";
/**
* 核心方法
*/
@Override
public Object intercept(Invocation invocation) throws Throwable {
boolean synchronizationActive = TransactionSynchronizationManager.isActualTransactionActive();
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];
String lookupKey = DynamicDataSourceHolder.DB_MASTER;
if (synchronizationActive != true) {
if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
lookupKey = DynamicDataSourceHolder.DB_MASTER;
} else {
BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("[\\t\\n\\r]", " ");
if (sql.matches(REGEX)) {
lookupKey = DynamicDataSourceHolder.DB_MASTER;
} else {
lookupKey = DynamicDataSourceHolder.DB_SLAVE;
}
}
}
} else {
lookupKey = DynamicDataSourceHolder.DB_MASTER;
}
DynamicDataSourceHolder.setDbType(lookupKey);
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties arg0) {
}
}
配置主從伺服器的位址:
為了友善,他們的使用者名和密碼都是一樣的
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.master.url=jdbc:mysql://192.168.111.134:3306/o2o?useUnicode=true&characterEncoding=utf8
jdbc.slave.url=jdbc:mysql://192.168.111.135:3306/o2o?useUnicode=true&characterEncoding=utf8
jdbc.username=work
jdbc.password=xuyiqing
mybatis-config.xml:Mybatis配置檔案:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
......
<!-- 自定義攔截器 -->
<plugins>
<plugin interceptor="org.dreamtech.o2o.dao.split.DynamicDataSourceInterceptor" />
</plugins>
......
</configuration>
spring-dao.xml配置檔案:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
......
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 資料源 -->
<bean id="abstractDataSource" abstract="true"
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="maxPoolSize" value="30" />
<property name="minPoolSize" value="10" />
<property name="autoCommitOnClose" value="false" />
<property name="checkoutTimeout" value="10000" />
<property name="acquireRetryAttempts" value="2" />
</bean>
<!-- 主資料庫 -->
<bean id="master" parent="abstractDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.master.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 從資料庫 -->
<bean id="slave" parent="abstractDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.slave.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置動态資料源 -->
<bean id="dynamicDataSource" class="org.dreamtech.o2o.dao.split.DynamicDataSource">
<property name="targetDataSources">
<map>
<entry value-ref="master" key="master"></entry>
<entry value-ref="slave" key="slave"></entry>
</map>
</property>
</bean>
<!-- 懶加載資料源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
<property name="targetDataSource">
<ref bean="dynamicDataSource" />
</property>
</bean>
......
</beans>