Spring+SpringMVC+MyBatis+MySQL 实现读写分离

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxdeng/article/details/83865560

简介

主从复制实现后,主库数据只能够写入数据,数据只能够从库数据完成。此时代码部分就需要实现读写分离;就需要配置多个数据源;而以前配置的DataSource 只能够从单一的URL中获取连接。在Spring 中提供了一个AbstractRoutingDataSource 类来可以帮我实现多个DataSource。AbstractRoutingDataSource 继承 AbstractDataSource,而 AbstractDataSource 实现了DataSource接口。在 AbstractRoutingDataSource中提供了一个determineTargetDataSource方法可以决定目标的方法使用那个DataSource。我们在使用读写分离只需要定义一个类继承 AbstractRoutingDataSource类重写里面determineCurrentLookupKey方法;此方法就用来动态获取数据源;

具体步骤如下

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 中间件,在程序和数据库之间实现读写分离

案例代码

猜你喜欢

转载自blog.csdn.net/hxdeng/article/details/83865560