Spring and MyBatis multi-data source configuration and management, springmybatis
The same project sometimes involves multiple databases, that is, multiple data sources. Multiple data sources can be divided into two situations:
1) two or more databases are independent of each other and can be developed as two projects. For example, in game development, a database is a platform database, and other databases for games under the platform are also available;
2) two or more databases are in the master-slave relationship. For example, if mysql is used to build a master-master database, multiple slave instances are subsequently created; or master-slave replication built using MHA;
Currently, I know there are two ways to set up Spring multi-data sources: You can select multiple data sources.
1. Use the spring configuration file to directly configure multiple data sources
For example, if there is no correlation between the two databases, you can directly configure multiple data sources in the spring configuration file and then configure transactions separately, as shown below:
<Context: component-scan base-package = "net. aazj. service, net. aazj. aop "/> <context: component-scan base-package =" net. aazj. aop "/> <! -- Introduce the property file --> <context: property-placeholder location = "classpath: config/db. properties"/> <! -- Configure the data source --> <bean name = "dataSource" class = "com. alibaba. druid. pool. druidDataSource "init-method =" init "destroy-method =" close "> <property name =" url "value =" $ {jdbc_url} "/> <property name =" username "value =" $ {jdbc_username} "/> <property name =" password "value =" $ {jdbc_password} "/> <! -- Initialize the connection size --> <property name = "initialSize" value = "0"/> <! -- Maximum number of connections used by the connection pool --> <property name = "maxActive" value = "20"/> <! -- Maximum idle connection pool --> <property name = "maxIdle" value = "20"/> <! -- Minimum idle connection pool --> <property name = "minIdle" value = "0"/> <! -- Get the maximum connection wait time --> <property name = "maxWait" value = "60000"/> </bean> <bean id = "sqlSessionFactory" class = "org. mybatis. spring. sqlSessionFactoryBean "> <property name =" dataSource "ref =" dataSource "/> <property name =" configLocation "value =" classpath: config/mybatis-config.xml "/> <property name =" mapperLocations "value =" classpath *: config/mappers /**/*. xml "/> </bean> <! -- Transaction manager for a single JDBC DataSource --> <bean id = "transactionManager" class = "org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" dataSource "/> </bean> <! -- Define a transaction using annotation --> <tx: annotation-driven transaction-manager = "transactionManager"/> <bean class = "org. mybatis. spring. mapper. mapperScannerConfigurer "> <property name =" basePackage "value =" net. aazj. mapper "/> <property name =" sqlSessionFactoryBeanName "value =" sqlSessionFactory "/> </bean>
<! -- Enables the use of the @ AspectJ style of Spring AOP --> <aop: aspectj-autoproxy/> <! -- =================== Configuration of the second data source ==================================--> <bean name = "cece_2" class = "com. alibaba. druid. pool. druidDataSource "init-method =" init "destroy-method =" close "> <property name =" url "value =" $ {jdbc_url_2} "/> <property name =" username "value =" $ {jdbc_username_2} "/> <property name =" password "value =" $ {jdbc_password_2} "/> <! -- Initialize the connection size --> <property name = "initialSize" value = "0"/> <! -- Maximum number of connections used by the connection pool --> <property name = "maxActive" value = "20"/> <! -- Maximum idle connection pool --> <property name = "maxIdle" value = "20"/> <! -- Minimum idle connection pool --> <property name = "minIdle" value = "0"/> <! -- Get the maximum connection wait time --> <property name = "maxWait" value = "60000"/> </bean> <bean id = "sqlSessionFactory_slave" class = "org. mybatis. spring. sqlSessionFactoryBean "> <property name =" dataSource "ref =" dataSource_2 "/> <property name =" configLocation "value =" classpath: config/mybatis-config-2.xml "/> <property name =" mapperLocations "value =" classpath *: config/mappers2 /**/*. xml "/> </bean> <! -- Transaction manager for a single JDBC DataSource --> <bean id = "transactionManager_2" class = "org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" cece_2 "/> </bean> <! -- Define a transaction using annotation --> <tx: annotation-driven transaction-manager = "transactionManager_2"/> <bean class = "org. mybatis. spring. mapper. mapperScannerConfigurer "> <property name =" basePackage "value =" net. aazj. mapper2 "/> <property name =" sqlSessionFactoryBeanName "value =" sqlSessionFactory_2 "/> </bean>
As shown above, we have configured two dataSource, two sqlSessionFactory, two transactionmanagers, and the key lies in the configuration of MapperScannerConfigurer-UseSqlSessionFactoryBeanNameProperty to inject the names of different sqlSessionFactory. In this way, the corresponding sqlSessionFactory is injected to the mapper interface of different databases.
Note that the configuration of multiple databases does not support distributed transactions, that is, the same transaction cannot operate on multiple databases. This configuration method has the advantages of being simple but not flexible. It is not suitable for master-slave-type multi-data source configuration. master-slave-type multi-data source configuration requires special flexibility and requires careful configuration based on the business type. For example, for some select statements that take a very large amount of time, we want to put them on slave for execution, while for update, delete and other operations, they must be executed only on the master, in addition, for some select statements with high real-time requirements, we may also need to put them on the master for execution-for example, in a scenario where I went to the mall to buy a weapon, and the purchase operation was always the master, at the same time, after the purchase is complete, you need to re-query the weapons and coins that I own, then this query may also need to prevent execution on the master, rather than on the slave for execution, because there may be latency on the slave, we do not want players to find that weapons cannot be found in the backpack after the purchase is successful.
Therefore, the configuration of multi-data sources of the master-slave type requires flexible configuration based on the business, which select can be placed on the slave, and which select cannot be placed on the slave. Therefore, the configuration of the data source above is not suitable.
2. configuration of multiple data sources based on AbstractRoutingDataSource and AOP
The basic principle is that we define a DataSource class ThreadLocalRountingDataSource to inherit the AbstractRoutingDataSource, inject data sources of the master and slave to ThreadLocalRountingDataSource in the configuration file, and then use AOP for flexible configuration, select the master data source and slave data source. The Code is as follows:
1)Define an enum to indicate different data sources:
Package net. aazj. enums;/*** data source category: master/slave */public enum DataSources {MASTER, SLAVE}
2)Use TheadLocal to save the identifier (key) of the Data Source selected by each thread ):
package net.aazj.util;import net.aazj.enums.DataSources;public class DataSourceTypeManager { private static final ThreadLocal<DataSources> dataSourceTypes = new ThreadLocal<DataSources>(){ @Override protected DataSources initialValue(){ return DataSources.MASTER; } }; public static DataSources get(){ return dataSourceTypes.get(); } public static void set(DataSources dataSourceType){ dataSourceTypes.set(dataSourceType); } public static void reset(){ dataSourceTypes.set(DataSources.MASTER0); }}
3)Defines ThreadLocalRountingDataSource and inherits the AbstractRoutingDataSource:
package net.aazj.util;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class ThreadLocalRountingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceTypeManager.get(); }}
4)Inject data sources of the master and slave into ThreadLocalRountingDataSource in the configuration file:
<Context: component-scan base-package = "net. aazj. service, net. aazj. aop "/> <context: component-scan base-package =" net. aazj. aop "/> <! -- Introduce the property file --> <context: property-placeholder location = "classpath: config/db. properties"/> <! -- Configure the data source Master --> <bean name = "cecemaster" class = "com. alibaba. druid. pool. druidDataSource "init-method =" init "destroy-method =" close "> <property name =" url "value =" $ {jdbc_url} "/> <property name =" username "value =" $ {jdbc_username} "/> <property name =" password "value =" $ {jdbc_password} "/> <! -- Initialize the connection size --> <property name = "initialSize" value = "0"/> <! -- Maximum number of connections used by the connection pool --> <property name = "maxActive" value = "20"/> <! -- Maximum idle connection pool --> <property name = "maxIdle" value = "20"/> <! -- Minimum idle connection pool --> <property name = "minIdle" value = "0"/> <! -- Get the maximum connection wait time --> <property name = "maxWait" value = "60000"/> </bean> <! -- Configure the data source Slave --> <bean name = "dataSourceSlave" class = "com. alibaba. druid. pool. druidDataSource "init-method =" init "destroy-method =" close "> <property name =" url "value =" $ {jdbc_url_slave} "/> <property name =" username "value =" $ {jdbc_username_slave} "/> <property name =" password "value =" $ {jdbc_password_slave} "/> <! -- Initialize the connection size --> <property name = "initialSize" value = "0"/> <! -- Maximum number of connections used by the connection pool --> <property name = "maxActive" value = "20"/> <! -- Maximum idle connection pool --> <property name = "maxIdle" value = "20"/> <! -- Minimum idle connection pool --> <property name = "minIdle" value = "0"/> <! -- Get the maximum connection wait time --> <property name = "maxWait" value = "60000"/> </bean> <bean id = "dataSource" class = "net. aazj. util. threadLocalRountingDataSource "> <property name =" defaultTargetDataSource "ref =" cecemaster "/> <property name =" targetDataSources "> <map key-type =" net. aazj. enums. dataSources "> <entry key =" MASTER "value-ref =" dataSourceMaster "/> <entry key =" SLAVE "value-ref =" dataSourceSlave "/> <! -- You can add multiple dataSource --> </map> </property> </bean> <bean id = "sqlSessionFactory" class = "org. mybatis. spring. sqlSessionFactoryBean "> <property name =" dataSource "ref =" dataSource "/> <property name =" configLocation "value =" classpath: config/mybatis-config.xml "/> <property name =" mapperLocations "value =" classpath *: config/mappers /**/*. xml "/> </bean> <! -- Transaction manager for a single JDBC DataSource --> <bean id = "transactionManager" class = "org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" dataSource "/> </bean> <! -- Define a transaction using annotation --> <tx: annotation-driven transaction-manager = "transactionManager"/> <bean class = "org. mybatis. spring. mapper. mapperScannerConfigurer "> <property name =" basePackage "value =" net. aazj. mapper "/> <! -- <Property name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory"/> --> </bean>
In the above spring configuration file, we have defined the dataSourceMaster and cesceslave dataSource for the master database and the slave database respectively, and then injected them to <bean id = "dataSource" class = "net. aazj. util. threadLocalRountingDataSource ">, so that our dataSource can select cecemaster and dataSourceSlave based on different keys.
5)Use Spring AOP to specify the dataSource key, so that dataSource selects dataSourceMaster and dataSourceSlave based on the key:
package net.aazj.aop;import net.aazj.enums.DataSources;import net.aazj.util.DataSourceTypeManager;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;@Aspect // for aop@Component // for auto scanpublic class DataSourceInterceptor { @Pointcut("execution(public * net.aazj.service..*.getUser(..))") public void dataSourceSlave(){}; @Before("dataSourceSlave()") public void before(JoinPoint jp) { DataSourceTypeManager.set(DataSources.SLAVE); }
// ... ...}
Here we define an Aspect class. We use @ Before to comply with @ Pointcut ("execution (public * net. aazj. service .. *. getUser (..)) ") before the method in is called, call cetcetypemanager. set (DataSources. SLAVE) sets the key type to DataSources. SLAVE, so dataSource will be based on key = CES. SLAVE: Select cesceslave as the dataSource. Therefore, the SQL statement for this method will be executed on the slave database.
We can constantly expand the performanceinterceptor Aspect and conduct various definitions in it to specify a proper dataSource for a method of a service.
In this way, we can use the powerful features of Spring AOP for flexible configuration.
6) AbstractRoutingDataSource Principle Analysis
ThreadLocalRountingDataSource inherits the AbstractRoutingDataSource and implements the abstract method protected abstract Object determineCurrentLookupKey (). This allows you to route different data sources. Let's start with the source code to analyze the principles:
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean
AbstractRoutingDataSourceIf InitializingBean is implemented, spring will call the InitializingBean interface when initializing the bean.
Void afterPropertiesSet () throws Exception;Let's take a look at how AbstractRoutingDataSource implements this interface:
@Override public void afterPropertiesSet() { if (this.targetDataSources == null) { throw new IllegalArgumentException("Property 'targetDataSources' is required"); } this.resolvedDataSources = new HashMap<Object, DataSource>(this.targetDataSources.size()); for (Map.Entry<Object, Object> entry : this.targetDataSources.entrySet()) { Object lookupKey = resolveSpecifiedLookupKey(entry.getKey()); DataSource dataSource = resolveSpecifiedDataSource(entry.getValue()); this.resolvedDataSources.put(lookupKey, dataSource); } if (this.defaultTargetDataSource != null) { this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource); } }
TargetDataSources is the dataSourceMaster and dataSourceSlave we inject in the xml configuration file.The afterPropertiesSet method uses the injection method.
DataSourceMaster and dataSourceSlave are used to construct a HashMap -- resolvedDataSources. This facilitates obtaining the corresponding dataSource from the map based on the key..
Let's take a look at how the Connection getConnection () throws SQLException in the AbstractDataSource interface is implemented:
@Override public Connection getConnection() throws SQLException { return determineTargetDataSource().getConnection(); }
The key lies in determineTargetDataSource (). According to the method name, we can see that the dataSource used is determined here:
protected DataSource determineTargetDataSource() { Assert.notNull(this.resolvedDataSources, "DataSource router not initialized"); Object lookupKey = determineCurrentLookupKey(); DataSource dataSource = this.resolvedDataSources.get(lookupKey); if (dataSource == null && (this.lenientFallback || lookupKey == null)) { dataSource = this.resolvedDefaultDataSource; } if (dataSource == null) { throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]"); } return dataSource; }
Object lookupKey = determineCurrentLookupKey (); this method is implemented to obtain the key value saved in ThreadLocal. After obtaining the key,
Obtain the dataSource corresponding to the key from the map resolvedDataSources initialized in afterPropertiesSet. The key value stored in ThreadLocal
It is set before calling related methods in the service through AOP. OK, you can do it now!
7) extended ThreadLocalRountingDataSource
The above is just the choice of the master-slave data source. If there are multiple masters or multiple slave instances. Multiple masters form one HA. To implement this function, when one master is down, it will automatically switch to another master. This function can be implemented using LVS/Keepalived, you can also implement it by further extending ThreadLocalRountingDataSource. You can add another thread to test whether mysql works normally every second. Server Load balancer is also required between multiple Server Load balancer instances. When one Server Load balancer instance is down, it must be removed from the Server Load balancer instance. This function can be achieved through LVS/Keepalived, you can also extend ThreadLocalRountingDataSource.
3. Summary
From this article, we can understand the strength and flexibility of AOP.
This article uses mybatis. In fact, using Hibernate should also be similar configuration.