1.在项目的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.新建动态切换数据源的类DynamicDataSource.java
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"; //----获取到当前正在执行的CurrentThread 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.在 applicationContext .xml中继续配置动态的数据源bean,在此我们使用springJdbc进行展示
<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> <!-- 默认使用数据源1 --> <property name="defaultTargetDataSource" ref="dataSource1"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>4.在代码中如果要切换数据源如下代码操作
@RequestMapping("/findUsers") @ResponseBody public Map<String, Object> findUsers(HttpServletRequest request,HttpServletResponse resp){ Map<String, Object> map = new HashMap<>(); //切换到数据源2,下面一行即可切换 DynamicDataSource.setCustomerType(DynamicDataSource.DATASOURCE2); List<Map<String, Object>> allUser = userDao.findAllUser(); map.put("code", 100); map.put("message", "查询成功"); map.put("list", allUser); return map; }