若依集成多数据源sqlserver
驱动包 放在admin模块的pom文件中
<!--sql server驱动-->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
修改数据源配置
application-druid.yml
# OMS数据源
oms:
enabled: true
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://xxx;DatabaseName=xxx;
username: xxx
password: xxx
其他配置修改
# 配置检测连接是否有效
validationQuery: SELECT 1
或者直接注释掉
#validationQuery: SELECT 1 FROM DUAL
直接注释掉还要注释掉 DruidProperties文中的
//@Value("${spring.datasource.druid.validationQuery}")
//private String validationQuery;
/**
* 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
*/
// datasource.setValidationQuery(validationQuery);
当时validationQuery
改成select * 一直报 “必须指定要从中选择的表。”
,一直以为是sql 写错了。
增加数据源枚举类型
DataSourceType
/**
* 数据源
*
* @author ruoyi
*/
public enum DataSourceType
{
/**
* 主库
*/
MASTER,
/**
* 从库
*/
SLAVE,
/**
* OMS数据库 SQL SERVER 数据库
*/
OMS
}
数据源读取注入 DruidConfig
@Bean
@ConfigurationProperties("spring.datasource.druid.oms")
@ConditionalOnProperty(prefix = "spring.datasource.druid.oms", name = "enabled", havingValue = "true")
public DataSource omsDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource)
{
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");
setDataSource(targetDataSources, DataSourceType.OMS.name(), "omsDataSource");
return new DynamicDataSource(masterDataSource, targetDataSources);
}
使用 在需要使用多数据源方法或类上添加@DataSource注解,其中value用来表示数据源
@DataSource(value = DataSourceType.SLAVE)
public List<SysUser> selectUserList(SysUser user)
{
return userMapper.selectUserList(user);
}
@Service
@DataSource(value = DataSourceType.SLAVE)
public class SysUserServiceImpl