To use a project, you need to integrate two different databases!
Paste the code for future use:
1. Create a static ing class that maps Dynamic Data sources
public class DataSourceMap { public static final String Analyse="Analyse"; public static final String DLmarket= "DLmarket"; }
2. Create a database connection and configure the container class
public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setCustomerType(String customerType){ contextHolder.set(customerType); } public static String getCustomerType() { return contextHolder.get(); } public static void clearCustomerType() { contextHolder.remove(); } }
3. Create a dynamic data source switch class
public class DynamicDataSource extends AbstractRoutingDataSource{ @Override protected Object determineCurrentLookupKey() { // TODO Auto-generated method stub String customerType=""; if(DataSourceContextHolder.getCustomerType()!=null){ customerType = DataSourceContextHolder.getCustomerType().toString(); } return customerType; } }
This class inherits the abstractroutingdatasource and overrides the determinecurrentlookupkey method.
4. Configure multiple data sources in spring
<Bean id = "analysedatasource" class = "com. alibaba. druid. pool. druiddatasource "init-method =" init "Destroy-method =" close "> <property name =" url "value =" $ {jdbc_url} "/> <property name =" username "value =" $ {jdbc_username} "/> <property name =" password "value =" $ {jdbc_password} "/> xxx... </bean> <bean id = "dlmarketdatasource" class = "com. alibaba. druid. pool. druiddatasource "init-method =" init "Destroy-method =" clo Se "> <property name =" url "value =" $ {jdbc_url_dlmarket} "/> <property name =" username "value =" $ {jdbc_username_dlmarket} "/> <property name = "password" value = "$ {jdbc_password_dlmarket}"/> xxx... <bean> <! -- Multi-data source ing --> <bean id = "datasource" class = "com. current. util. dynamicdatasource "> <property name =" targetdatasources "> <map key-type =" Java. lang. string "> <! -- The key value must be the same as the value in the static key-value control class. & nbsp; --> <entry value-ref = "analysedatasource" Key = "analyse"> </entry> <entry value-ref = "dlmarketdatasource" Key = "dlmarket"> </entry> </map> </property> <property name = "defaulttargetdatasource" ref = "analysedatasource"> </property> </bean>
Other sessionfactory Transaction Manager configurations do not need to be modified.
5. Switch data sources in action
public void getList(){ DataSourceContextHolder.setCustomerType(DataSourceMap.DLmarket); int id=1; List<Chaining> chainList = chainService.getList(id); System.out.println(chainList.get(0).getChaining()); }
Configure a dynamic data source using SSH