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;