目前有个需求,需要使用不同的数据源,例如某业务要用A数据源,另一个业务要用B数据源。
如何在spring框架中解决多数据源的问题
使用springboot 整合多数据源 遇到的坑
1、添加依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.0version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.1version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
2、application.properties配置文件
#主数据库
master:
db:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://47.111.22.159:3306/xinyar_erp_uat?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
username: erp_test
password: erp_test@abc
#从数据库
slave:
db:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://47.111.22.159:3306/erp-test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
username: erp_test
password: erp_test@abc
mybatis:
mapper-locations: classpath*:com/xinyartech/erp/*/xml/*/*.xml
type-aliases-package: com.xinyartech.erp.*.model,com.xinyartech.erp.*.vo
configuration:
map-underscore-to-camel-case: true
3、禁用springboot默认加载数据源配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
4、主数据源配置类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
/**
* 主数据源
*
* @author Lynch
*
*/
@Configuration
@ConfigurationProperties(prefix = "master.db")
@Data
public class MasterDataSourceConfig {
@Value("${master.db.url}")
private String url;
@Value("${master.db.username}")
private String username;
@Value("${master.db.password}")
private String password;
@Value("${master.db.driverClassName}")
private String driverClassName;
}
5、从数据源配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import lombok.Data;
/**
* 从数据源
*
* @author Lynch
*
*/
@Configuration
@ConfigurationProperties(prefix = "slave.db")
@Data
public class SlaveDataSourceConfig {
@Value("${slave.db.url}")
private String url;
@Value("${slave.db.username}")
private String username;
@Value("${slave.db.password}")
private String password;
@Value("${slave.db.driverClassName}")
private String driverClassName;
}
6、数据源配置类
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
/**
* 数据源配置类
*
* @author Lynch
*/
@Configuration
public class DataSourceComponent {
@Resource
private MasterDataSourceConfig masterDataSourceConfig;
@Resource
private SlaveDataSourceConfig slaveDataSourceConfig;
@Bean(name = "master")
public DataSource masterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(masterDataSourceConfig.getUrl());
dataSource.setUsername(masterDataSourceConfig.getUsername());
dataSource.setPassword(masterDataSourceConfig.getPassword());
dataSource.setDriverClassName(masterDataSourceConfig.getDriverClassName());
return dataSource;
}
@Bean(name = "slave")
public DataSource slaveDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(slaveDataSourceConfig.getUrl());
dataSource.setUsername(slaveDataSourceConfig.getUsername());
dataSource.setPassword(slaveDataSourceConfig.getPassword());
dataSource.setDriverClassName(slaveDataSourceConfig.getDriverClassName());
return dataSource;
}
@Primary//不加这个会报错。
@DependsOn({ "master", "slave"}) //解决数据库循环依赖问题
@Bean(name = "multiDataSource")
public MultiRouteDataSource exampleRouteDataSource() {
MultiRouteDataSource multiDataSource = new MultiRouteDataSource();
Map
7、数据源上下文
/**
* 数据源上下文
*
* @author Lynch
*/
public class DataSourceContext {
private static final ThreadLocal contextHolder = new ThreadLocal<>();
public static void setDataSource(String value) {
contextHolder.set(value);
}
public static String getDataSource() {
return contextHolder.get();
}
public static void clearDataSource() {
contextHolder.remove();
}
}
8、DataSource路由类
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import com.xinyartech.erp.config.DataSourceContext;
/**
* DataSource路由类
*
* 重写的函数决定了最后选择的DataSource
*
* @author Lynch
*/
public class MultiRouteDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// 通过绑定线程的数据源上下文实现多数据源的动态切换,有兴趣的可以去查阅资料或源码
return DataSourceContext.getDataSource();
}
}
9、修改上下文中的数据源就可以切换自己想要使用的数据源了
public UserVO findUser(String username) {
DataSourceContext.setDataSource("slave");
UserVO userVO = userMapper.findByVO(username);
System.out.println(userVO.getName());
return null;
}
这种是在业务中使用代码设置数据源的方式,也可以使用AOP+注解的方式实现控制,还可以前端头部设置后端通过拦截器统一设置!