一个学习加记录的博客!
一、第一步
在application-druid.yml里配置多个库的连接设置
# 主库数据源
master:
url: jdbc:mysql://111.111.111.1111:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: root
# 从库数据源1
slave:
# 从数据源开关/默认关闭
enabled: true
url: jdbc:mysql://111.111.111.1111:3306/test1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: root
# 从库数据源2
slaveData:
# 从数据源开关/默认关闭
enabled: true
url: jdbc:mysql://111.111.111.1111:3306/test3?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: root
# 从库数据源3
...........................................................................
2.第二步
在ruoyi-common下的DataSourceType里配置数据源
3.第三步
修改ruoyi-framework下的DruidConfig文件
@Bean
@ConfigurationProperties("spring.datasource.druid.slave") //这里就是从库1
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slaveData") //这里就是从库2
@ConditionalOnProperty(prefix = "spring.datasource.druid.slaveData", name = "enabled", havingValue = "true")
public DataSource slaveData(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");//从库1
setDataSource(targetDataSources, DataSourceType.SLAVEDATA.name(), "slaveData");//从库2
return new DynamicDataSource(masterDataSource, targetDataSources);
}
3.最后一步
在service上加上@DataSource(value = DataSourceType.MASTER)这个注解 DataSourceType.就是你想要连的那一个库
注:如果需要生成代码的也需要用到注解,生成那个库的表就用那个,GenController