1. Configure multiple data sources in the project's applicationContext.xml
<bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property> <property name="url"><value>jdbc:mysql://localhost:3306/test</value></property> <property name="username"><value>root</value></property> <property name="password"><value>myadmin</value></property> </bean> <bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property> <property name="url"><value>jdbc:mysql://localhost:3306/test2</value></property> <property name="username"><value>root</value></property> <property name="password"><value>myadmin</value></property> </bean>
2. Create a new class DynamicDataSource.java for dynamically switching data sources
package com.springmvc.config; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { public static final String DATASOURCE1 = "dataSource1"; public static final String DATASOURCE2 = "dataSource2"; //----Get the CurrentThread that is currently executing public 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(); } @Override protected Object determineCurrentLookupKey() { return getCustomerType(); } }
3. Continue to configure dynamic data source beans in applicationContext.xml , where we use springJdbc to display
<bean id="dataSource" class="com.springmvc.config.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry value-ref="dataSource1" key="dataSource1"></entry> <entry value-ref="dataSource2" key="dataSource2"></entry> </map> </property> <!-- Use data source 1 by default --> <property name="defaultTargetDataSource" ref="dataSource1"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>4. If you want to switch the data source in the code, do the following code operation
@RequestMapping("/findUsers") @ResponseBody public Map<String, Object> findUsers(HttpServletRequest request,HttpServletResponse resp){ Map<String, Object> map = new HashMap<>(); //Switch to data source 2, the following line can switch DynamicDataSource.setCustomerType(DynamicDataSource.DATASOURCE2); List<Map<String, Object>> allUser = userDao.findAllUser(); map.put("code", 100); map.put("message", "Query successful"); map.put("list", allUser); return map; }