1 Due to the requirements of the project, data from different sources need to be stored in different databases, so data sources need to be dynamically switched according to the input information

The core layer of the project adopts the framework of Spring + Mybitas

1 Define two data sources in the Spring configuration


2 Create a new class MultiDataSource

public class MultiDataSource extends AbstractRoutingDataSource {

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

public static void setDataSourceKey(String dataSource) {
    dataSourceKey.set(dataSource);
}

@Override
protected Object determineCurrentLookupKey() {
    return dataSourceKey.get();
}Copy the code

}

This class needs to inherit AbstractRoutingDataSource and rewrite determineCurrentLookupKey method 3 new configuration in the spring configuration file


  <map key-type="java.lang.String ">
     <entry value-ref="dataSource1 " key="dataSource1 "></entry>
     <entry value-ref="dataSource2 " key="dataSource2 "></entry>
  </map>Copy the code






4 Add the configured dataSource to sessionFactory

5 Inject sessionFactory into sqlSession

It is decided to use Spring-AOP to add pointcuts for dynamic switching

Public Class DataBaseAop {

Public void before(InputObject InputObject,OutputObject OutputObject){if(condition){Copy the code

MultiDataSource.setDataSourceKey(“dataSource1 “);

}else{

MultiDataSource.setDataSourceKey(“dataSource2 “);

}

}Copy the code

} 6.2 Define data switching classes

6.3 Defining the pointcut

  <aop:before method="before " pointcut-ref="dataBase " arg-names="inputObject,outputObject " />Copy the code

The proxy-target-class=”true “argument sets the interceptor to be class

Note 1 AbstractRoutingDataSource class with database resources exist in the method of establishing a Connection public Connection getConnection ()

In this method calls the protected DataSource determineTargetDataSource () method

In this method will be called determineCurrentLookupKey the key access to the dataBase and on the basis of the key from the corresponding data source to obtain the corresponding dataBase connection resources Such as database connection pool resources MultiDataSource rewritten DetermineCurrentLookupKey method

@Override
protected Object determineCurrentLookupKey() {
    return dataSourceKey.get();
}
Copy the code

Before the need to switch data call global method MultiDataSource. SetDataSourceKey (String key) to switch the data source

2

  <map key-type="java.lang.String ">
     <entry value-ref="dataSource1 " key="dataSource1 "></entry>
     <entry value-ref="dataSource2 " key="dataSource2 "></entry>
  </map>Copy the code

The key in the tag in the configuration is the key of the dynamically switched data source. The defaultTargetDataSource parameter refers to the default data source