若依框架(前后端分离)——多数据源配置详细教程
planScheduleService是类名,selectMoInfo()则是在后面定义的。这样在前端发送请求,便可以获取成功了,以上便是配置数据源的具体流程例子。文件路径图片:配置处1——注意:框住了的即为需要注意并修改的地方。impl文件内的类配置,注意。文件路径图片:配置处2。
·
此篇写的是对若依框架中的多数据源的配置教程,看了很多教程,很多都是写的较为模糊,以下是自己配置时的详细的步骤,大家可以根据这个例子去实现连接:
1. 在ruoyi-admin文件中的xml文件内配置数据库的信息。
将账号和密码等服务器信息配置进去,1443是SQL server默认的服务器端口:
2.在DataSourceType枚举文件内增加自己配置的数据源。
3.在DruidConfig中增加数据源加载
@Configuration
public class DruidConfig
{
@Bean
@ConfigurationProperties("spring.datasource.druid.master")
public DataSource masterDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@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.selectmo")
@ConditionalOnProperty(prefix = "spring.datasource.druid.selectmo", name = "enabled", havingValue = "true")
public DataSource selectmoDataSource(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");
//将新的数据源对象加载到DataSource去
setDataSource(targetDataSources, DataSourceType.SELECTMO.name(), "selectmoDataSource");
return new DynamicDataSource(masterDataSource, targetDataSources);
}
文件路径图片:配置处1——注意:框住了的即为需要注意并修改的地方
文件路径图片:配置处2
4.添加操作数据源的方法
5.在Controller中进行配置
@GetMapping("/getmo") // 调用的是get请求,/getmo是路由地址
public String getMoInfo() {
String[] moInfoArr = planScheduleService.selectMoInfo();
System.out.println(moInfoArr.length);
// 对数据进行操作
return "hello"; // 将需要的数据进行返回
}
planScheduleService是类名,selectMoInfo()则是在后面定义的
6. 在mapper中配置
@Select("SELECT * FROM XXX") // 需要执行的SQL语句
public String[] selectMoInfo(); // 返回值的类型需要与control中的保持一致
SQL语句一方面是写在mapper内,一方面是写在对应的xml文件内:
7. service文件配置
接口文件配置:
public String[] selectMoInfo();
impl文件内的类配置,注意在此处使用需要调用的数据源:
@Override
@DataSource(value = DataSourceType.SELECTMO)
public String[] selectMoInfo() {
return planScheduleMapper.selectMoInfo();
}
这样在前端发送请求,便可以获取成功了,以上便是配置数据源的具体流程例子。
更多推荐
已为社区贡献2条内容
所有评论(0)