springboot多数据源集成
- 1、添加依赖
- 2、添加配置
- 3、代码使用
- 4、动态切换数据库
1、添加依赖
<!--多数据源-->
<dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.4.0</version>
</dependency>
2、添加配置
spring:application:name: iotdata-systemdatasource:dynamic:primary: iothub #设置默认的数据源或者数据源组,默认值即为iothubstrict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源datasource: iothub:url: jdbc:postgresql://120.46.33.xxx:9100/xxx1username: postgrespassword: xxxxxxxxdatahub:url: jdbc:postgresql://120.46.33.xxx:9100/xxx2username: postgrespassword: xxxxxxxx
3、代码使用
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.iot.system.common.mvc.IMapper;
import com.iot.system.datahub.entity.DbConn;
import org.apache.ibatis.annotations.Mapper;@Mapper
@DS("datahub")//@DS 指定数据源名称,可以用在mapper上 service上 或者某个方法上
public interface DbConnMapper extends BaseMapper<DbConn>, IMapper<DbConn> {
}
4、动态切换数据库
使用Hutool
DataSource ds = new SimpleDataSource("jdbc:postgresql://120.46.33.xxx:9100/xxx", Username, Password);try {return Db.use(ds).query("select * from xxx");} catch (SQLException e) {e.printStackTrace();}finally{try {DbUtil.close(ds.getConnection());} catch (SQLException e) {e.printStackTrace();}}return null;