目前有个需求,需要使用不同的数据源,例如某业务要用A数据源,另一个业务要用B数据源。
如何在spring框架中解决多数据源的问题
使用springboot 整合多数据源 遇到的坑
1、添加依赖
<!-- 阿里的druid 依赖log4j -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 引入mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</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<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put("master", masterDataSource());
targetDataSources.put("slave", slaveDataSource());
multiDataSource.setTargetDataSources(targetDataSources);
multiDataSource.setDefaultTargetDataSource(masterDataSource());
return multiDataSource;
}
/**
* 注册ServletRegistrationBean
*
* @return
*/
@Bean
public ServletRegistrationBean druidServlet() {
ServletRegistrationBean reg = new ServletRegistrationBean();
reg.setServlet(new StatViewServlet());
reg.addUrlMappings("/druid/*");
reg.addInitParameter("allow", ""); // 白名单 return reg;
reg.addInitParameter("loginUsername", "duan");
reg.addInitParameter("loginPassword", "123456");
reg.addInitParameter("resetEnable", "false");
return reg;
}
/**
* 注册FilterRegistrationBean
*
* @return
*/
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
filterRegistrationBean.addInitParameter("profileEnable", "true");
filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");
filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION");
filterRegistrationBean.addInitParameter("DruidWebStatFilter", "/*");
return filterRegistrationBean;
}
}
7、数据源上下文
/**
* 数据源上下文
*
* @author Lynch
*/
public class DataSourceContext {
private static final ThreadLocal<String> 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+注解的方式实现控制,还可以前端头部设置后端通过拦截器统一设置!