基于Spring+Mybatis的多数据源动态切换

Spring单数据源直接在<bean id="dataSource">下配置数据源的各种连接参数。但动态数据源需要配置个各个数据源例如ds1、ds2等。然后在dataSource中动态根据传递过来的参数动态调用不同的数据源。 

1、当进行访问时,首先通过DbContextHolder.setDbType("ds1");设置需要使用的数据源。DbContextHolder就是一个用来存储数据源信息的类,其中通过ThreadLocal来记录数据源信息。 

2、DynamicDataSource类集成Spring的AbstractRoutingDataSource类,通过determineCurrentLookupKey方法来获取数据源类型,如果没有对应的数据源则使用defaultTargetDataSource配置。 

注意:当设置了数据源之后会一直使用该数据源进行连接,除非使用 DbContextHolder.setDbType重新设置数据源或使用DbContextHolder.clearDbType()清除,清除后使用defaultTargetDataSource进行连接。 

1、配置文件 

properties 

  1. ds1.driverClassName=oracle.jdbc.OracleDriver  
  2. ds1.url=jdbc:oracle:thin:@localhost:1521:ORCL  
  3. ds1.username=SSM  
  4. ds1.password=SSM  
  5.   
  6. ds2.driverClassName=oracle.jdbc.OracleDriver  
  7. ds2.url=jdbc:oracle:thin:@10.27.192.43:1522:ORCL  
  8. ds2.username=FRAMEWORK_DEV  
  9. ds2.password=123456  
xml 

  1. <bean id="dataSource" class="com.cnpc.framework.db.DynamicDataSource">  
  2.         <property name="targetDataSources">  
  3.             <map key-type="java.lang.String">  
  4.                 <entry key="ds1" value-ref="ds1" />  
  5.                 <entry key=
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用 AbstractRoutingDataSource 和 MyBatis 拦截器实现动态切换数据的示例代码: 首先,需要自定义一个继承 AbstractRoutingDataSource 的类,并实现 determineCurrentLookupKey 方法,该方法用于返回当前数据的 key: ```java public class DynamicDataSource extends AbstractRoutingDataSource { private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<>(); public static void setDataSourceKey(String key) { dataSourceKey.set(key); } @Override protected Object determineCurrentLookupKey() { return dataSourceKey.get(); } } ``` 在 Spring 配置文件中需要配置两个数据,并将 DynamicDataSource 设置为默认数据: ```xml <bean id="dataSource1" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db1"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <bean id="dataSource2" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db2"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <bean id="dynamicDataSource" class="com.example.DynamicDataSource"> <property name="defaultTargetDataSource" ref="dataSource1"/> <property name="targetDataSources"> <map> <entry key="db1" value-ref="dataSource1"/> <entry key="db2" value-ref="dataSource2"/> </map> </property> </bean> ``` 接下来,需要实现一个继承于 MyBatis 的 Interceptor 接口的拦截器类,该类用于在执行 SQL 语句前切换数据: ```java @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) public class DynamicDataSourceInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); MetaObject metaObject = SystemMetaObject.forObject(statementHandler); MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); String dataSourceKey = getDataSourceKey(mappedStatement); if (dataSourceKey != null) { DynamicDataSource.setDataSourceKey(dataSourceKey); } return invocation.proceed(); } private String getDataSourceKey(MappedStatement mappedStatement) { String dataSourceKey = null; // 从 Mapper 方法上获取数据 key if (mappedStatement != null) { String id = mappedStatement.getId(); if (id.startsWith("com.example.mapper1")) { dataSourceKey = "db1"; } else if (id.startsWith("com.example.mapper2")) { dataSourceKey = "db2"; } } return dataSourceKey; } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { // do nothing } } ``` 最后,需要在 Spring 配置文件中配置该拦截器: ```xml <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dynamicDataSource"/> <property name="plugins"> <array> <bean class="com.example.DynamicDataSourceInterceptor"/> </array> </property> </bean> ``` 这样,就可以在 Mapper 方法上使用 @DataSource("db1") 或 @DataSource("db2") 注解来指定使用哪个数据了。例如: ```java @DataSource("db1") List<User> getUserList(); @DataSource("db2") int addUser(User user); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值