在MyBatis中配置Druid多数据源主要需要进行以下步骤:
- 首先,在pom.xml文件中添加Druid和MyBatis的依赖:
com.alibaba druid 1.1.23 org.mybatis mybatis 3.5.6
- 然后在application.properties或者application.yml文件中配置Druid的数据源信息,例如:
spring.datasource.druid.datasource1.url=jdbc:mysql://localhost:3306/test1 spring.datasource.druid.datasource1.username=root spring.datasource.druid.datasource1.password=root spring.datasource.druid.datasource2.url=jdbc:mysql://localhost:3306/test2 spring.datasource.druid.datasource2.username=root spring.datasource.druid.datasource2.password=root
- 创建DruidDataSource配置类,用于配置Druid数据源:
@Configuration public class DruidDataSourceConfig { @Bean(name = "dataSource1") @ConfigurationProperties(prefix = "spring.datasource.druid.datasource1") public DataSource dataSource1() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "dataSource2") @ConfigurationProperties(prefix = "spring.datasource.druid.datasource2") public DataSource dataSource2() { return DruidDataSourceBuilder.create().build(); } @Bean @Primary public DynamicDataSource dataSource(@Qualifier("dataSource1") DataSource dataSource1, @Qualifier("dataSource2") DataSource dataSource2) { Map
- 创建DynamicDataSource类,用于动态切换数据源:
public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSource(); } }
- 创建DataSourceContextHolder类,用于设置数据源的key:
public class DataSourceContextHolder { private static final ThreadLocalcontextHolder = new ThreadLocal<>(); public static void setDataSource(String key) { contextHolder.set(key); } public static String getDataSource() { return contextHolder.get(); } public static void clearDataSource() { contextHolder.remove(); } }
通过以上步骤,就可以实现在MyBatis中配置Druid多数据源。在需要切换数据源的地方,可以通过调用DataSourceContextHolder.setDataSource("dataSource2")
来切换到相应的数据源。