美文网首页
spring控制数据库读写分离(多数据源动态切换)

spring控制数据库读写分离(多数据源动态切换)

作者: 换她笑面如花 | 来源:发表于2018-11-06 22:40 被阅读0次

问题描述:

项目一直是使用同一个数据库进行读和写的操作,在写操作时会锁表,并且效率低,后期出现性能问题

原因描述:

项目只能操作一个数据源

需求描述:

配置多个数据源,利用切面进行动态切换

解决方案:

修改配置,并且增加切面进行自动控制

解决方式:

第一步:配置多个数据源:

 数据源1

<!-- 数据源 -->

<bean id="DataSource1" class="com.alibaba.druid.pool.DruidDataSource"

init-method="init" destroy-method="close">

<property name="driverClassName" value="${jdbc.driverClass}" />

<property name="url" value="${jdbc.url}" />

<property name="username" value="${jdbc.user}" />

<property name="password" value="${jdbc.password}" />

<property name="filters" value="stat" />

<property name="maxActive" value="1000" />

<property name="initialSize" value="1" />

<property name="maxWait" value="80000" />

<property name="minIdle" value="1" />

<!-- 超过时间限制是否回收 -->

<property name="removeAbandoned" value="true" />

<!-- 超时时间;单位为秒。120秒=2分钟 -->

<property name="removeAbandonedTimeout" value="120" />

<!-- 关闭abanded连接时输出错误日志 -->

<!-- <property name="logAbandoned" value="true" /> -->

<property name="timeBetweenEvictionRunsMillis" value="60000" />

<property name="minEvictableIdleTimeMillis" value="300000" />

<property name="validationQuery" value="SELECT 'x'" />

<property name="testWhileIdle" value="true" />

<property name="testOnBorrow" value="false" />

<property name="testOnReturn" value="false" />

<property name="defaultAutoCommit" value="true" />

</bean>

数据源2

<!-- 数据源 -->

<bean id="DataSource2" class="com.alibaba.druid.pool.DruidDataSource"

init-method="init" destroy-method="close">

<property name="driverClassName" value="${jdbc.driverClass}" />

<property name="url" value="${jdbc.url2}" />

<property name="username" value="${jdbc.user}" />

<property name="password" value="${jdbc.password}" />

<property name="filters" value="stat" />

<property name="maxActive" value="1000" />

<property name="initialSize" value="1" />

<property name="maxWait" value="80000" />

<property name="minIdle" value="1" />

<!-- 超过时间限制是否回收 -->

<property name="removeAbandoned" value="true" />

<!-- 超时时间;单位为秒。120秒=2分钟 -->

<property name="removeAbandonedTimeout" value="120" />

<!-- 关闭abanded连接时输出错误日志 -->

<!-- <property name="logAbandoned" value="true" /> -->

<property name="timeBetweenEvictionRunsMillis" value="60000" />

<property name="minEvictableIdleTimeMillis" value="300000" />

<property name="validationQuery" value="SELECT 'x'" />

<property name="testWhileIdle" value="true" />

<property name="testOnBorrow" value="false" />

<property name="testOnReturn" value="false" />

<property name="defaultAutoCommit" value="true" />

</bean>

第二步:配置选择数据源的bean

a.配置数据源切换的bean

<bean id="dataSource" class="com.zsrt.devbase.datesource.DynamicDataSource">

<property name="targetDataSources">

<map key-type="java.lang.String">

<entry value-ref="DataSource1" key="testDataSource1"></entry>

<entry value-ref="DataSource2" key="testDataSource2"></entry>

</map>

</property>

<property name="defaultTargetDataSource" ref="testDataSource1" />

</bean>

 class 为自定义的数据源切换控制的bean

在map中,key指向的是后台需要选择的数据源名称,value指向的是第一步配置的数据源id

b.编写切换控制器

/**

* 数据源的切换与选择器

* @author leixin

* @Date 2017年4月19日

* @version 1.0

*/

public class DataSourceContextHolder {

private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

/**

* @Description: 设置数据源类型

* @param dataSourceType 数据库类型

* @return void

* @throws

*/

public static void setDataSourceType(String dataSourceType) {

System.err.println(dataSourceType);

contextHolder.set(dataSourceType);

}

/**

* @Description: 获取数据源类型

* @param

* @return String

* @throws

*/

public static String getDataSourceType() {

return contextHolder.get();

}

/**

* @Description: 清除数据源类型

* @param

* @return void

* @throws

*/

public static void clearDataSourceType() {

contextHolder.remove();

}

}

c.编写切换控制器

public class DynamicDataSource extends AbstractRoutingDataSource {

@Override

protected Object determineCurrentLookupKey() {

return DataSourceContextHolder.getDataSourceType();

}

}

以上步骤已经完成数据库的手动切换,在控制层可以手动切换。

具体切换方法为:当需要调用数据源A时,用静态的类去设置数据源A的名字,然后再去调用service

问题:每次都需要手动切换,有点麻烦,因此想到利用切面控制

在上面的基础上利用切面控制,最先想到的是切面控制service,但是控制service会和事务控制切面产生冲突(原因是事务需要锁定数据源的链接,而当前的数据源链接还没有进行动态切换,所以只能选择默认的数据源,从而导致切换失败)

思路一:

于是想到切面切入点为控制层,在开启事务之前就切换数据源。

思路二:

      利用@order注解控制切面的执行顺序

经过上面的分析,思路二明显优于思路一,于是开始尝试思路二,在思路二的基础上,打算开启注解切入

第一步:自定义切面注解:     

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public @interface DataSource {

}

第二步:编写切面:

@Aspect

@Order(0)

public class DataSourceAspect{

@AfterReturning("execution(* com.zsrt.devbase.service.*.*(..))")

public void afterReturning() throws Throwable {

DataSourceContextHolder.clearDataSourceType();

}

@Before("execution(* com.zsrt.devbase.service.*.*(..)) && @annotation(com.zsrt.devbase.annotation.DataSource)")

public void before(JoinPoint jp) throws Throwable {

DataSourceContextHolder.setDataSourceType("testDataSource2");

}

}

第三步:配置事务切面的执行顺序:

<aop:config>

<!-- 切点表达式:所有的service类中的方法都会有事务 -->

<aop:pointcut id="appService"

expression="execution(* com.zsrt.devbase.service.*Service*.*(..))" />

<aop:advisor advice-ref="txAdvice" pointcut-ref="appService" order="1" />

</aop:config>

结果:

经测试,程序按照预期进行执行:

先切换了数据源,然后开启了事务,最后再执行了别的切面

---------------------

原文:https://blog.csdn.net/leixin821792669/article/details/70242397

相关文章

网友评论

      本文标题:spring控制数据库读写分离(多数据源动态切换)

      本文链接:https://www.haomeiwen.com/subject/ebipxqtx.html