SpringBoot怎么使用druid配置多数据源
作者:小宇宙叶知秋
时间:2023-05-11
来源:互联网
浏览:0
一、背景使用springboot配置多数据源,数据源分别为postgresql、mysql二、版本介绍springboot——2.5.4druid——1.2.11postgresql——12mysql——8.0.16maven——3.0idea——2019三、项目结构javapackage目录resource目录存放mapper.xml文件,按照数据源创建pack
一、背景
使用spring boot配置多数据源,数据源分别为postgresql、mysql
二、版本介绍
spring boot——2.5.4
druid——1.2.11
postgresql——12
mysql——8.0.16
maven——3.0
idea——2019
三、项目结构
java package目录

resource目录存放mapper.xml文件,按照数据源创建package

四、maven依赖
org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web com.alibaba fastjson 2.0.4 com.alibaba druid-spring-boot-starter 1.2.11 org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2 org.postgresql postgresql runtime mysql mysql-connector-java
五、yaml配置文件
server: port: 8081 spring: datasource: type: com.alibaba.druid.pool.DruidDataSource druid: web-stat-filter: enabled: true #是否启用StatFilter默认值true url-pattern: /* exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico session-stat-enable: true session-stat-max-count: 10 stat-view-servlet: enabled: true #是否启用StatViewServlet默认值true url-pattern: /druid/* reset-enable: true login-username: admin login-password: admin allow: db1: username: postgres password: localhost url: jdbc:postgresql://localhost:5432/test driver-class-name: org.postgresql.Driver initial-size: 5 # 初始化大小 min-idle: 5 # 最小 max-active: 100 # 最大 max-wait: 60000 # 配置获取连接等待超时的时间 validation-query: select version() time-between-eviction-runs-millis: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 min-evictable-idle-time-millis: 300000 # 指定一个空闲连接最少空闲多久后可被清除,单位是毫秒 filters: config,wall,stat # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=false test-while-idle: true test-on-borrow: true test-on-return: false # 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 db2: username: root password: localhost url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver initial-size: 5 # 初始化大小 min-idle: 5 # 最小 max-active: 100 # 最大 max-wait: 60000 # 配置获取连接等待超时的时间 validation-query: select 'x' time-between-eviction-runs-millis: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 min-evictable-idle-time-millis: 300000 # 指定一个空闲连接最少空闲多久后可被清除,单位是毫秒 filters: config,wall,stat # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=false test-while-idle: true test-on-borrow: true test-on-return: false # 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 mybatis: mapper-locations: classpath:com/demo/mapper/*.xml type-aliases-package: com.demo.entity configuration: log-impl: mapUnderscoreToCamelCase: true #showSql logging: level: java.sql: debug org.apache.ibatis: debug com.demo.mapper: debug config: classpath:logback-spring.xml
六、数据源配置文件
@Configuration
@MapperScan(basePackages = "com.demo.mapper.postgre.**", sqlSessionFactoryRef = "oneSqlSessionFactory")
public class DataSourceConfig1 {
// 将这个对象放入Spring容器中
@Bean(name = "oneDataSource")
// 表示这个数据源是默认数据源
@Primary
// 读取application.properties中的配置参数映射成为一个对象
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.druid.db1")
public DataSource getDateSource1() {
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
@Bean(name = "oneSqlSessionFactory")
// 表示这个数据源是默认数据源
@Primary
// @Qualifier表示查找Spring容器中名字为oneDataSource的对象
public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 设置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.postgre/*.xml"));
return bean.getObject();
}
@Bean("oneSqlSessionTemplate")
// 表示这个数据源是默认数据源
@Primary
public SqlSessionTemplate oneSqlSessionTemplate(
@Qualifier("oneSqlSessionFactory") SqlSessionFactory sessionFactory) {
return new SqlSessionTemplate(sessionFactory);
}
}@Configuration
@MapperScan(basePackages = "com.demo.mapper.mysql", sqlSessionFactoryRef = "twoSqlSessionFactory")
public class DataSourceConfig2 {
// 将这个对象放入Spring容器中
@Bean(name = "twoDataSource")
// 读取application.properties中的配置参数映射成为一个对象
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.druid.db2")
public DataSource getDateSource1() {
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
@Bean(name = "twoSqlSessionFactory")
// 表示这个数据源是默认数据源
//@Primary
// @Qualifier表示查找Spring容器中名字为oneDataSource的对象
public SqlSessionFactory oneSqlSessionFactory(@Qualifier("twoDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 设置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.mysql/*.xml"));
return bean.getObject();
}
@Bean("twoSqlSessionTemplate")
// 表示这个数据源是默认数据源
//@Primary
public SqlSessionTemplate oneSqlSessionTemplate(
@Qualifier("twoSqlSessionFactory") SqlSessionFactory sessionFactory) {
return new SqlSessionTemplate(sessionFactory);
}
}七、启动类配置
关键点:去除 exclude = {DataSourceAutoConfiguration.class} 及扫描 com.demo.mapper目录
@MapperScan("com.demo.mapper")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication .class, args);
}
}八、druid管理页面
输入地址 localhost://8081/druid,输入 admin/admin
作者最新文章
极度公式
2026-09-16 17:43
索尼WH-1000XM4C发布:复刻经典折叠设计并升级现代接口
2026-09-08 19:10
PDF转TXT操作步骤与转换后内容核对指南
2026-09-04 18:03
Photoshop安装失败或启动异常:系统要求、安装流程与故障排查指南
2026-09-03 06:04
PDF文件体积过大如何压缩及压缩后清晰度检查方法
2026-09-02 19:30
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















