Implement database read/write splitting using spring

Source: Internet
Author: User

And real-time data query, Slave database is certainly responsible for non-real-time data query. In actual applications, databases only read more and write less (the frequency of reading data is high, and the frequency of updating data is relatively small), while reading data usually takes a long time, the CPU usage of the database server is high, which affects the user experience. The common practice is to extract the query from the master database, use multiple slave databases, and use Server Load balancer to relieve the query pressure on each slave database.

.

, Which is read when querying data. This method is simple and I will not go into details.

, Spring AOP ,. The implementation method is described in detail below.

Class

It was added after spring2.0. Let's first look at the definition:

It is a child of DataSource. Is the data source interface of javax. SQL, which is defined as follows:

DataSourceView Code

The interface defines two methods to obtain database connections. Let's see how to implement the interface:

Connection getConnection () Connection getConnection (String username, String password)View Code

Obviously, you can call your own determineTargetDataSource () method to obtain the connection. The determineTargetDataSource method is defined as follows:

. ResolvedDataSources, "DataSource router not initialized" ==( dataSource == &&(. lenientFallback | lookupKey = (dataSource = IllegalStateException ("Cannot determine target DataSource for lookup key [" + lookupKey + "]"View Code

We are most concerned with the following two sentences:

Object lookupKey = determineCurrentLookupKey ();
DataSource dataSource = this. resolvedDataSources. get (lookupKey );

The determineCurrentLookupKey method returns the lookupKey. The resolvedDataSources method obtains the data source from the Map based on the lookupKey. ResolvedDataSources and determineCurrentLookupKey are defined as follows:

Private Map <Object, DataSource> resolvedDataSources;

Protected abstract Object determineCurrentLookupKey ()

If we see the above definition, is it a bit of thought? resolvedDataSources is of the Map type. We can save MasterDataSource and SlaveDataSource to Map, as shown below:

Key value

Master MasterDataSource

Slave SlaveDataSource

We are writing a DynamicDataSource class that inherits the AbstractRoutingDataSource and implements its determineCurrentLookupKey () method. This method returns the Map key, master, or slave.

 

Well, it's a bit annoying to say so much. Let's take a look at how to implement it.

The technology we want to use has been mentioned above. Let's first look at the definition of annotation:

@View Code

We also need to implement the spring abstract class AbstractRoutingDataSource, which is to implement the determineCurrentLookupKey method:

DynamicDataSource ThreadLocal <String> holder = ThreadLocal <String>View Code

From the definition of DynamicDataSource, the returned value is DynamicDataSourceHolder. getDataSouce (). We need to call the DynamicDataSourceHolder. putDataSource () method when the program is running and assign values to it. The following is the core part of our implementation, that is, the AOP part. DataSourceAspect is defined as follows:

==<?> [] Classz = <?> [] ParameterTypes = classz [0 (m! = & M. isAnnotationPresent (DataSource. =View Code

To facilitate the test, I have defined two databases: shop simulation Master database and test simulation Slave database. The table structure of shop and test is the same, but the data is different. The database configuration is as follows:

View Code

Add the aop configuration in spring Configuration

= "Com. air. shop. proxy. performanceaspect "/> <aop: config> <aop: aspect id =" c "ref =" manyperformanceaspect "> <aop: pointcut id = "tx" expression = "execution (* com. air. shop. mapper. *. *(..)) "/> <aop: before pointcut-ref =" tx "method =" before "/> </aop: aspect> </aop: config> <! -- Configure the database annotation aop -->View Code

The following is the definition of UserMapper of MyBatis. To facilitate the test, the Master database is read during login and the Slave database is read from the user list:

"Master" delete ("slave" User loadbyid ("master" "slave" List <User>View Code

Okay. Run Eclipse to check the effect. Enter the User Name admin to log on to the system to check the effect.

  

  

We can see that the data in the logon user list is different from that in the user list. It also verifies our implementation. The logon reads the Master database, and the user list reads the Slave database.

 

Thank you for reading this article. I hope this article will help you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.