Spring configures multiple data sources

Source: Internet
Author: User

 Spring Multi-data source configuration
 1. Add several data sources to the spring configuration file: 
<bean id= "TestDataSource1" class= "Org.apache.commons.dbcp.BasicDataSource" >
<property name= "Driverclassname" value= "Oracle.jdbc.driver.OracleDriver"/>
<property name= "url" va Lue= "JDBC:ORACLE:THIN:@//127.0.0.1:1521/ORCL"/>
<property name= "username" value= "test1"/>
< Property name= "Password" value= "123456"/>
<property name= "maxactive" value= "/>";
<property Nam E= "Maxidle" value= "ten"/>
<property name= "maxwait" value= "" "/>
<property name=" Defaultautocomm It "value=" true "/>
</bean>
 <bean id= "TestDataSource2" class= "Org.apache.commons.dbcp.BasicDataSource"; 
<property name= " Driverclassname "value=" Oracle.jdbc.driver.OracleDriver "/>
<property name=" url "value=" Jdbc:oracle:thin: @//127.0.0.1:1521/orcl "/>
<property name=" username "value=" test2 "/>
<property name=" Password "va Lue= "123456"/>
<property name= "maxactive" value= "/>";
<property name= "Maxidle" value= "ten"/> ;
<property name= "maxwait" value= "+"/>
<property name= "Defaultautocommit" value= "true"/>
& L T;/bean>,


2, and then combine the data sources:

<!--combined data source
<bean id= "DataSource" class= "Com.baoan.project.dao.hibernate.DynamicDataSource" >
<property name= "Targetdatasources" >
<map key-type= "Java.lang.String" >
<entry key= "
TestDataSource1 "value-ref=" TestDataSource1 "/>
<entry key= " value-ref= "
 </map>
</property>
<!--to a default data source configuration-
<property name= "Defaulttargetdatasource" ref=
" TestDataSource1 " />
</bean>
3. Then expand a spring-provided abstractroutingdatasource,override which Determinecurrentlookupkey method implements the route of the data source.

[Java]
  1. Package datasource;
  2. Import Org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
  3. Public class Dynamicdatasource extends abstractroutingdatasource{
  4. @Override
  5. protected Object Determinecurrentlookupkey () {
  6. return Customercontextholder.getcustomertype ();
  7. }
  8. }
And Customercontextholder This is a developer's own implementation of a package of the threadlocal type of Contextholder

[Java]
  1. Package datasource;
  2. Public class Customercontextholder {
  3.     public static  final string data_source_a =  "testdatasource1 " ;      
  4. Public static final String data_source_a = "TestDataSource2";    
  5. private static final threadlocal<string> Contextholder = new threadlocal<string> ();
  6. public static void Setcustomertype (String customertype) {
  7. Contextholder.set (CustomerType);
  8. }
  9. public static String Getcustomertype () {
  10. return Contextholder.get ();
  11. }
  12. public static void Clearcustomertype () {
  13. Contextholder.remove ();
  14. }
  15. }

5. How is this dynamic multi-data source used? Actually very simple, because our dynamicdatasource is inherited with Abstractroutingdatasource, And Abstractroutingdatasource is inherited in Org.springframework.jdbc.datasource.AbstractDataSource, the obvious Abstractdatasource realizes the unification Datasour Ce interface, so our dynamicdatasource can also be conveniently used as a DataSource, take hibernate below as an example:

[HTML]View Plaincopy
[Java]View Plaincopy
  1. <bean id="sessionfactory" class=" Org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean ">
  2. <!--can see the same as normal datasource usage--
  3. <property name="DataSource" ref="Dynamicdatasource"/>
  4. <property name="configlocations" value="Classpath:hibernate.cfg.xml"/>
  5. <property name="Hibernateproperties" >
  6. <props>
  7. <prop key="Hibernate.dialect" >${hibernate.dialect}</prop>
  8. </props>
  9. </property>
  10. </bean>
It can be seen that we are still using a sessionfactory, so the configuration of transaction management is the same as before.

[HTML]View Plaincopy
  1. <tx:annotation-driven transaction-manager="TransactionManager"/>
  2. <Bean id= "transactionmanager" class=" Org.springframework.orm.hibernate3.HibernateTransactionManager ">
  3. <property name= "sessionfactory" ref="sessionfactory" />
  4. </Bean>

The Dynamicdatasource Bean is also in the container, and now the rest is in the program to control how to choose a desired data source to do:

[Java]View Plaincopy
    1. This dynamically sets the data source to DATASOURCEB.
    2. Customercontextholder.setcustomertype (customercontextholder.data_source_b);
or using AOP to implement
[Java] view Plaincopy  
  1. Package datasource;
  2. Import Org.aspectj.lang.JoinPoint;
  3. Import Org.aspectj.lang.annotation.Aspect;
  4. Import Org.aspectj.lang.annotation.Before;
  5. Import Org.aspectj.lang.annotation.Pointcut;
  6. @Aspect
  7. Public class Dynamicdatasourceaspect {
  8. @Pointcut ("Execution (public Service.impl). *.*(..))")  
  9. public void Serviceexecution () {}
  10. @Before ("serviceexecution ()")
  11. public void Setdynamicdatasource (Joinpoint jp) {
  12. For (Object O:jp.getargs ()) {
  13. //Handle specific logic, according to the specific situation customercontextholder.setcustomertype () Select DataSource
  14. }
  15. }
[Plain]View Plaincopy
    1. 6. Summary: We can see that the use of abstractroutingdatasource can be very good to implement a multi-data source, and later to expand more data sources is also very easy, as long as the data source and modify Dynamicdatasource The Bean's targetdatasources configuration is good. On the selection of a data source, in fact, can be very good with @aspect in the service entrance to join a plane @pointcut, In @before, judge the Joinpoint's class capacity to select a specific data source (for example, a more Joinpoint key to determine the setting Customercontextholder.setcustomertype).
    2. Genjiu the actual application to determine. Personal view: There have been many applications where Writedatasource and Readdatasource and Slavedatabase implementations have been deployed, but most of the applications are now less suited to the architecture, More and more attention and user interaction makes synchronization between the database become increasingly complex and difficult to maintain, so in the architecture of the system may consider the use of horizontal cutting method to cut the database, of course, this development needs more time to analyze the business domain, choose how to configure the data source is actually related to the business.

Spring configures multiple data sources

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.