Dynamic switching of multiple data sources based on Spring+mybatis

Source: Internet
Author: User

The spring single data source configures various connection parameters for the data source directly under <bean id= "DataSource" >. However, a dynamic data source needs to be configured with individual data sources such as DS1, DS2, and so on. Then dynamically invoke different data sources in datasource based on the parameters passed in.

1, when the access, first through Dbcontextholder.setdbtype ("DS1"), set the data source to use. Dbcontextholder is a class used to store data source information, in which data source information is recorded through Threadlocal.

2, Dynamicdatasource class integrates spring's Abstractroutingdatasource class, obtains the data source type through the Determinecurrentlookupkey method, If there is no corresponding data source, use the Defaulttargetdatasource configuration.

Note: When the data source is set, the data source is used to connect, unless you use Dbcontextholder.setdbtype to reset the data source or use Dbcontextholder.cleardbtype () cleanup. After purging, use Defaulttargetdatasource to connect.

1. Configuration files

Properties

Ds1.driverclassname=oracle.jdbc.OracleDriver  ds1.url=jdbc:oracle:thin: @localhost:1521 : ORCL  ds1.username=SSM  ds1.password=SSM    ds2.driverclassname=  Oracle.jdbc.OracleDriver  ds2.url=jdbc:oracle:thin:@10.27. 192.43:1522: ORCL  ds2.username=Framework_dev  ds2.password =123456  

Xml

<bean id="DataSource" class="Com.cnpc.framework.db.DynamicDataSource"> <property name="targetdatasources"> <map key-type="java.lang.String"> <entry key="DS1"value-ref="DS1"/> <entry key="DS2"value-ref="DS2"/> </map> </property> <property name="Defaulttargetdatasource" ref="DS1"/> </bean> <bean id="DS1" class="Org.apache.commons.dbcp.BasicDataSource"Destroy-method="Close"> <property name="Driverclassname"Value="${ds1.driverclassname}"/> <property name="URL"Value="${ds1.url}"/> <property name="username"Value="${ds1.username}"/> <property name="Password"Value="${ds1.password}"/> </bean> <bean id="DS2" class="Org.apache.commons.dbcp.BasicDataSource"Destroy-method="Close"> <property name="Driverclassname"Value="${ds2.driverclassname}"/> <property name="URL"Value="${ds2.url}"/> <property name="username"Value="${ds2.username}"/> <property name="Password"Value="${ds2.password}"/> </bean>

2. java files
Com.cnpc.framework.db.DynamicDataSource Source

 Public classDynamicdatasource extends Abstractroutingdatasource {/** * Get the current data source used. */@OverrideprotectedObject Determinecurrentlookupkey () {returnDbcontextholder.getdbtype (); }               PublicLogger Getparentlogger () {//TODO auto-generated Method Stub        return NULL; }        }  

Dbcontextholder Source

 Public classDbcontextholder {Private StaticFinal threadlocal<string> Contextholder =NewThreadlocal<string>(); /** * Set the current database. * @param dbType*/       Public Static voidSetdbtype (String dbType) {Contextholder.Set(DbType); }        /** * Get current data source. * @return*/       Public Staticstring Getdbtype () {string str= (String) contextholder.Get(); returnstr; }            /** * Clear Contextual data*/       Public Static voidCleardbtype () {contextholder.remove (); }        }  

3. Test code

 PublicModelandview List (httpservletrequest request, httpservletresponse response) throws Exception {Dbcontexth Older.setdbtype ("DS1"); List<DemoSysUser> List1 =Demosysuserservice.getall (); System. out. println (Dbcontextholder.getdbtype () +". List.size () ="+list1.size ()); Dbcontextholder.setdbtype ("DS2"); List<DemoSysUser> List2 =Demosysuserservice.getall (); System. out. println (Dbcontextholder.getdbtype () +". List.size () ="+list2.size ());                    Dbcontextholder.cleardbtype (); List<DemoSysUser> list =Demosysuserservice.getall (); Modelandview MV= This. Getautoview (). AddObject ("sysuserlist", list); returnMV; }  


get ""  

Dynamic switching of multiple data sources based on Spring+mybatis

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.