Multiple data source issues are common, such as reading and writing detached database configurations.
The original project has new requirements, the Bureau requested a new server to provide a code, involving a multi-data source problem.
The research results are as follows:
1. Configure multiple DataSource First
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" > <property name= "Driverclassname" value= "Net.sourceforge.jtds.jdbc.Driver" ></property> <property name= "url" value= "Jdbc:jtds:sqlserver://10.82.81.51:1433;databasename=standards" > </property><property name= "username" value= "youguess" ></property><property name= "Password" value= "youguess" ></property></bean><bean id= "DataSource2" class= "Org.apache.commons.dbcp.BasicDataSource" > <property name= " Driverclassname " value=" net.sourceforge.jtds.jdbc.Driver "></property><property name=" url " value=" Jdbc:jtds:sqlserver://10.82.81.52:1433;databasename=standards "></property><property name= "username" value= "youguess" ></property><property name= "password" value= " Youguess "></property></bean>
2. Write a Dynamicdatasource class to inherit Abstractroutingdatasource, and implement the Determinecurrentlookupkey method
Package Com.standard.core.util;import Org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class Dynamicdatasource extends Abstractroutingdatasource {@Overrideprotected Object Determinecurrentlookupkey () {return Customercontextholder.getcustomertype ();}}
3, using threadlocal to solve thread safety problems
package com.standard.core.util;public class customercontextholder {public static final string data_source_a = "DataSource";p ublic static final string data_source_b = "DataSource2"; private static final threadlocal<string> contextholder = new Threadlocal<string> ();p ublic static void setcustomertype (string customertype) { Contextholder.set (CustomerType);} Public static string getcustomertype () {return contextholder.get ();} Public static void clearcustomertype () {contextholder.remove ();}}
4. Data source Configuration
<bean id= "Dynamicdatasource" class= "Com.standard.core.util.DynamicDataSource" ><property name= " Targetdatasources "><map key-type=" java.lang.String "><entry value-ref=" DataSource "key=" DataSource " ></entry><entry value-ref= "DataSource2" key= "DataSource2" ></entry></map></property ><property name= "Defaulttargetdatasource" ref= "DataSource" ></property></bean>
5. Switch the data source in Daoimpl
Customercontextholder.setcustomertype (Customercontextholder.data_source_b);
Get!
Solve problems with multiple data sources with spring's Abstractroutingdatasource