First, preface
A recent project a need to synchronize data to another project B database, without changing the B project, had to choose project A to switch the data source, directly write the data to Project B's database. This requirement is often required in data synchronization and timing tasks.
So the question is, how do you solve a multi-data source problem? Not only to configure multiple data sources, but also to be flexible and dynamic switching of data sources. Take the Spring+hibernate framework project as an example (citation: Picture of http://blog.csdn.net/wangpeng047/article/details/8866239 blog):
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/59/F1/wKioL1TxHqHQ_2EIAAA2t2DPtbc761.jpg "title=" 20130429104020090.jpg "alt=" Wkiol1txhqhq_2eiaaa2t2dptbc761.jpg "/>
A single data source is bound to sessionfactory, and then to the DAO layer, if there are multiple data sources, that is not the case:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/59/F1/wKioL1TxH1-yOkTCAAB1EzUwMXo661.jpg "title=" 20130429105150794.jpg "alt=" Wkiol1txh1-yoktcaab1ezuwmxo661.jpg "/>
Visible, Sessionfactory are written dead in the DAO layer, if I add another data source, then you have to add a sessionfactory. So the better thing to do is:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/59/F1/wKioL1TxIC-gAVlAAABpRIiqH-w927.jpg "title=" 20130429111107055.jpg "alt=" Wkiol1txic-gavlaaabpriiqh-w927.jpg "/>
The next step is to explain how to use spring to integrate these data sources, as well as spring+hibernate configuration as an example.
Second, the realization principle
1. Extend spring's Abstractroutingdatasource abstract class (this class acts as a routing intermediary for DataSource, and can dynamically switch to a real datasource at run time based on some key value. )
From the source code of Abstractroutingdatasource:
Public abstract class Abstractroutingdatasource extends Abstractdatasource implements Initializingbean
We can see that it inherits the Abstractdatasource, and Abstractdatasource is not the subclass of Javax.sql.DataSource, so we can analyze its Getconnection method:
Public Connection getconnection () throws SQLException {return Determinetargetdatasource (). getconnection (); } Public Connection getconnection (string Username, string password) throws SQLException {return determinetargetd Atasource (). getconnection (username, password); }
Get the connection method, the focus is Determinetargetdatasource () method, look at the source:
/** * retrieve the current target datasource. determines the * {@link #determineCurrentLookupKey () current lookup key}, performs * a lookup in the {@link #setTargetDataSources targetDataSources} map, * falls back to the specified * {@link #setDefaultTargetDataSource default target datasource} if necessary . * @see #determineCurrentLookupKey () */ protected datasource determinetargetdatasource () { assert.notnull (This.resolvedDataSources, "Datasource router&nbsP;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; }
The main point of the above source is the Determinecurrentlookupkey () method, which is an abstract method in the Abstractroutingdatasource class, and its return value is the key value of the data source datasource you want to use, With this key value, Resolveddatasource (this is a map, which is stored in the configuration file) will be taken out of the corresponding DataSource, if not found, it is used to configure the default data source.
after reading the source code, it should be a little inspiration, right! You want to extend the Abstractroutingdatasource class and override the Determinecurrentlookupkey () method in it to implement a switchover of the data source :
Package Com.datasource.test.util.database;import org.springframework.jdbc.datasource.lookup.abstractroutingdatasource;/** * Get data source (dependent on spring) * @author linhy */public Class Dynamicdatasource extends abstractroutingdatasource{@Override protected Object Determinecurrentlookupkey () { return Datasourceholder.getdatasource (); }}
The
datasourceholder class is the class we encapsulate to manipulate the data source:
package com.datasource.test.util.database;/** * Data source Operations * @author linhy */ public class datasourceholder { //Thread Local Environment private static final ThreadLocal<String> dataSources = new ThreadLocal< String> (); //Set data source public static void Setdatasource (String customertype) { datasources.set ( CustomerType) } //get data source public Static string getdatasource () { return ( String) datasources.get (); } //Clear Data source public static void cleardatasource () { datasources.remove (); }}
2, some people will ask, then you setdatasource this method is to be executed at what time? Of course it does when you need to switch the data source. Do you call write dead manually in your code? This is a stupid way, of course, to make it dynamic. So we can use spring AOP to set, the configuration of the data source type is set as the annotation label, in the service layer need to switch the data source method, write the note tag, call the appropriate method to switch the data source (just as you set the transaction):
@DataSource (name=datasource.slave1) public List getproducts () {
Of course, the use of annotation tags may be very few people use, but it is a good thing oh, greatly helped us to develop:
Package Com.datasource.test.util.database;import java.lang.annotation.*; @Target ({Elementtype.method, Elementtype.type}) @Retention (retentionpolicy.runtime) @Documentedpublic @interface DataSource {String name () default Datasource.master; public static String master = "DataSource1"; public static String slave1 = "DataSource2"; public static String slave2 = "DataSource3";}
Iii. Configuration Files
To streamline the space, the configuration that is irrelevant to the topic of this content is omitted.
Separate the application-database.xml in the project, about the data source configuration files.
<?xml version= "1.0" encoding= "UTF-8"?><!-- Spring Database related configuration put here --> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "http ://www.springframework.org/schema/aop " xmlns:tx="/http Www.springframework.org/schema/tx " xsi:schemalocation=" http// www.springframework.org/schema/beans http://www.springframework.org/ schema/beans/spring-beans.xsd http://www.springframework.org/schema/ aop http://www.springframework.org/schema/aop/ Spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://wwW.springframework.org/schema/tx/spring-tx-3.0.xsd "> <bean id = " DataSource1 " class = " Com.mysql.jdbc.jdbc2.optional.MysqlDataSource "> <property name= "url" value= "${db1.url}"/> <property name = "User" value = "${db1.user}"/> <property name = " Password " value = " ${db1.pwd} "/> <property name= "AutoReConnect" value= "true"/> <property name= "Useunicode" value= "true"/> < Property name= "characterencoding" value= "UTF-8"/> </bean> <bean id = "DataSource2" class = "Com.mysql.jdbc.jdbc2.optional.MysqlDataSource" > <property name= "url" value= "${db2.url}"/> <property name = "User" value = "${ Db2.user} "/> <property name = " password " value = "${db2.pwd}"/> <property Name= "AutoReConnect" value= "true"/> <property Name= "Useunicode" value= "true"/> <property name= "characterencoding" value= "UTF-8"/> </bean> <bean id = "DataSource3" class = " Com.mysql.jdbc.jdbc2.optional.MysqlDataSource "> &nbSp; <property name= "url" value= "${db3.url}"/> <property name = "User" value = "${db3.user}"/> <property name = "Password" value = "${db3.pwd}"/> <property name= "AutoReconnect" value= "true"/> <property name= "UseUnicode" value= "true"/> <property name= " Characterencoding " value=" UTF-8 "/> </bean> <!-- Configuring a multi-data source mapping relationship --> <bean id= "DataSource" class= " Com.datasource.test.util.database.DynamicDataSource "> < Property name= "Targetdatasources" >&nbsP; <map key-type= "Java.lang.String" > <entry key= "DataSource1" value-ref= " DataSource1 "></entry> <entry key= "DataSource2" value-ref= "DataSource2" ></entry> <entry key= " DataSource3 " value-ref=" DataSource3 "></entry> </map> </property> <!-- Default Target data source is your main library data source --> < Property name= "Defaulttargetdatasource" ref= "DataSource1"/> </bean> <bean Id= "Sessionfactoryhibernate" class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean" > <property name= "DataSource" ref= "DataSource"/> <property name= "Hibernateproperties" > <props> <prop key= "Hibernate.dialect" > com.datasource.test.util.database.extendedmysqldialect</prop> <prop key= "Hibernate.show_sql" >${SHOWSQL}< /prop> < prop key= "Hibernate.format_sql" >${SHOWSQL}</prop> <prop key= "Query.factory_class" > org.hibernate.hql.classic.classicquerytranslatorfactory</prop> <prop key= "Hibernate.connection.provider_class" >org.hibernate.connection.C3P0ConnectionProvider</prop> <prop key= "Hibernate.c3p0.max_size" >30</ prop> < prop key= "Hibernate.c3p0.min_size" >5</prop> <prop key= "Hibernate.c3p0.timeout" >120</prop> <prop key= "Hibernate.c3p0.idle_test_period" >120</prop> &nbSp; <prop key= " Hibernate.c3p0.acquire_increment ">2</prop> <prop key= "Hibernate.c3p0.validate" >true</prop> <prop key= "Hibernate.c3p0.max_statements" >100</prop> </props> </property> </bean> <bean id= "Hibernatetemplate" class= " Org.springframework.orm.hibernate3.HibernateTemplate "> < Property name= "Sessionfactory" ref= "Sessionfactoryhibernate"/> </bean > <bean id= "Datasourceexchange " class=" Com.datasource.test.util.database.DataSourceExchange "/> <bean id= "TransactionManager" class= " Org.springframework.orm.hibernate3.HibernateTransactionManager "> <property name= "Sessionfactory" ref= "Sessionfactoryhibernate"/> </bean> <tx:advice id= "Txadvice" transaction-manager= " TransactionManager "> <tx:attributes> <tx:method name= "insert*" propagation= " NESTED " rollback-for=" Exception "/> <tx:method name= "add*" propagation= "NESTED" rollback-for= "Exception"/> <tx:method name= "Update* " propagation=" NESTED " rollback-for=" Exception "/> <tx:method name= "modify*" propagation= "NESTED" rollback-for= " Exception "/> <tx:method name = "edit*" propagation= "NESTED" rollback-for= "Exception"/> <tx:method name= "del*" propagation= "NESTED" rollback-for = "Exception"/> <tx:method Name= "save*" propagation= "NESTED" rollback-for= "Exception"/> <tx:method name= "send*" propagation= "NESTED" Rollback-for= "Exception"/>&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;<TX: Method name= "get*" read-oNly= "true"/> <tx:method name = "find*" read-only= "true"/> <tx:method name= "query*" read-only= "true"/> <tx:method name= "search*" read-only= "true"/> <tx:method name= "select*" read-only= "true"/> <tx:method name= "count*" Read-only= "true"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id= "service" expression= "Execution (* com.datasource. *.service.*.* (..)) " /> <!-- Key configuration, switching the data source must be performed more first than the Persistence layer code (the transaction also counts the persistence layer code) --> <aop:advisor advice-ref= "Txadvice" pointcut-ref= "service" Order= "2"/> <aop:advisor advice-ref= " Datasourceexchange " pointcut-ref=" service " order=" 1 "/> </aop:config> </beans>
Iv. questions
Multi-data source switching is successful, but involves a transaction? Single data source transactions are OK, but what if multiple data sources need to use a single transaction at the same time? This question has the nod big, some people on the network proposed using the Atomikos Open source project realizes the JTA Distributed transaction processing. What do you think?
This article is from the "Learning and Thinking" blog, please be sure to keep this source http://linhongyu.blog.51cto.com/6373370/1615895
Spring (Abstractroutingdatasource) for dynamic Data source switching