It is often necessary to connect multiple databases in real-world projects, and different business requirements often require access to different databases during the implementation process.
Jdbc.properties configuration files, configuring multiple DataSource
######################### #MySQL #################################### #hibernate. dialect= Org.hibernate.dialect.mysqlinnodbdialectconnection.driver_class=com.mysql.jdbc.driverconnection.url=jdbc:mysql ://localhost:3306/test?useunicode=true&characterencoding=utf-8connection.username= yahuconnection.password=123456######################### #Oracle ##################################### Connection1.driver_class=oracle.jdbc.driver.oracledriverconnection1.url=jdbc\:oracle\:thin\: @localhost \:1521/ medbconnection1.username=yahuconnection1.password=123456######################### #Sql Server2008############### ##################### #connection2. Driver_class=net.sourceforge.jtds.jdbc.driverconnection2.url=jdbc:jtds: sqlserver://localhost:1433;databasename=testconnection2.username=yahuconnection2.password=123456
Spring-config.xml the configuration file as follows, add the Dynamicdatasource bean to the spring context XML configuration file, and configure the Dynamicdatasource targetdatasources ( Multiple data source target) attribute map map, using Dynamic Data source Dynamicdatasource is inherited with Abstractroutingdatasource, And Abstractroutingdatasource is inherited in the Org.springframework.jdbc.datasource.abstractdatasource,abstractdatasource to achieve a unified datasource connected Port, so dynamicdatasource can also be used as a DataSource:
<!--database Connection Pool configuration - <BeanID= "DataSource"class= "Org.apache.commons.dbcp.BasicDataSource"> < Propertyname= "Driverclassname"value= "${connection.driver_class}" /> < Propertyname= "url"value= "${connection.url}" /> < Propertyname= "username"value= "${connection.username}" /> < Propertyname= "Password"value= "${connection.password}" /> < Propertyname= "InitialSize"value= "5" /> < Propertyname= "Minidle"value= "1" /> < Propertyname= "Maxactive"value= "$" /> <!--Configure the time to get the connection wait timeout - < Propertyname= "Maxwait"value= "30000" /> <!--How often the configuration interval is detected to detect idle connections that need to be closed, in milliseconds - < Propertyname= "Timebetweenevictionrunsmillis"value= "60000" /> <!--configures the minimum lifetime of a connection in a pool, in milliseconds - < Propertyname= "Minevictableidletimemillis"value= "300000" /> </Bean> <!--Oracle - <BeanID= "DataSource1"class= "Org.apache.commons.dbcp.BasicDataSource"> < Propertyname= "Driverclassname"value= "${connection1.driver_class}" /> < Propertyname= "url"value= "${connection1.url}" /> < Propertyname= "username"value= "${connection1.username}" /> < Propertyname= "Password"value= "${connection1.password}" /> </Bean> <!--SQL Server - <BeanID= "DataSource2"class= "Org.apache.commons.dbcp.BasicDataSource"> < Propertyname= "Driverclassname"value= "${connection2.driver_class}" /> < Propertyname= "url"value= "${connection2.url}" /> < Propertyname= "username"value= "${connection2.username}" /> < Propertyname= "Password"value= "${connection2.password}" /> </Bean> <!--Dynamic Data Sources - <BeanID= "Dynamicdatasource"class= "Com.yahu.core.dao.DynamicDataSource"> <!--correlate data sources in the form of Key-value - < Propertyname= "Targetdatasources"> <Map> <entryValue-ref= "DataSource"Key= "DataSource" /> <entryValue-ref= "DataSource1"Key= "Datasource1" /> <entryValue-ref= "DataSource2"Key= "Datasource2" /> </Map> </ Property> < Propertyname= "Defaulttargetdatasource"ref= "DataSource" /> </Bean>
Dynamicdatasource Dynamic Data source class, expands spring's Abstractroutingdatasource abstract class, implements the dynamic Data source, The abstract method in Abstractroutingdatasource Determinecurrentlookupkey is the core of the route that implements the data source. Override this method here:
PackageCom.yahu.core.dao;ImportOrg.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;/******************************************************************* * @describe: Creating a Dynamic Data source class Must inherit Abstractroutingdatasource ********************************************************************/ Public classDynamicdatasourceextendsAbstractroutingdatasource {//coverity Modification//Private Log log = Logfactory.getlog (GetClass ()); protectedObject Determinecurrentlookupkey () {String value=Customercontextholder.getcustomertype (); //Log.info (value); returnvalue; }}
Get and set the context for a thread-safe threadlocal:
PackageCom.yahu.core.dao;/******************************************************************* * @describe: Obtaining and setting the context environment ******************** ************************************************/ Public classCustomercontextholder {/*** MySQL*/ Public Static FinalString DATASOURCE = "DATASOURCE"; /*** Oracle*/ Public Static FinalString datasource_1 = "Datasource1"; /*** SQL Server*/ Public Static FinalString datasource_2 = "Datasource2"; Private Static FinalThreadlocal<string> Contextholder =NewThreadlocal<string>(); Public Static voidSetcustomertype (String customertype) {contextholder.set (customertype); } Public StaticString Getcustomertype () {returnContextholder.get (); } Public Static voidClearcustomertype () {contextholder.remove (); }}
Dynamic Data source management, how to choose to control the specific data sources needed in each business, can use manual control, the business layer by adding the following code
Customercontextholder.setcustomertype (Customercontextholder.datasource);
Can be implemented to dynamically switch the data source, if there is a uniform rule at the service layer, it is also possible to use AOP to set up a data source to use, which is generally a service one data source, so it is best to use AOP after the service layer is finished executing the unified call
customercontextholder. Clearcustomertype ();
Clears the data source information.
Of course, in the above configuration there is a parameter defaulttargetdatasource is the default data source, that is, do not set the data source, is to use this data source.
Spring integrates multiple data sources for dynamic switching