在springBoot框架下使用druid+myBatisPlus实现多数据源(不同模块不同数据源)
Posted 官萧何
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在springBoot框架下使用druid+myBatisPlus实现多数据源(不同模块不同数据源)相关的知识,希望对你有一定的参考价值。
1.idea新建多模块springBoot项目
父项目使用maven的方式创建
创建完成 删掉src目录
新增子模块使用springBoot initializer插件创建
按以上步骤再建module2 和 main
2.配置项目
因为父项目用的是maven方式 所以自己修改父项目pom文件 增加druid、mybatisPlus等依赖和module标签 以下是修改后的parent 的pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>cn.gch</groupId> <artifactId>druid-parent</artifactId> <version>1.0</version> <packaging>pom</packaging> <name>druid-parent</name> <modules> <module>druid-main</module> <module>druid-module1</module> <module>druid-module2</module> </modules> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- mybatis-plus begin --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.1</version> </dependency> <!-- mybatis-plus end --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </project>
子模块继承父模块并引入子模块 这里例出main模块的pom
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>cn.gch</groupId> <artifactId>druid-parent</artifactId> <version>1.0</version> </parent> <groupId>com.gch</groupId> <artifactId>druid-main</artifactId> <version>0.0.1-SNAPSHOT</version> <name>druid-main</name> <packaging>jar</packaging> <description>druid-main</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>com.gch</groupId> <artifactId>druid-module1</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gch</groupId> <artifactId>druid-module2</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3.在main模块 resource包下创建application.yml
#JDBC基本配置 server: port: 8088 spring: datasource: druid: #数据源1 datasource1: url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8&allowPublicKeyRetrieval=true username: root password: 123 driverClassName: com.mysql.cj.jdbc.Driver #数据源2 datasource2: #MyISAM和InnoDB是两种最常用的数据库引擎,默认的引擎是MyISAM,性能最好,但不支持事务处理,只有InnoDB支持事务 url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8&allowPublicKeyRetrieval=true username: root password: 123 driverClassName: com.mysql.cj.jdbc.Driver #连接池配置 initial-size: 5 max-active: 100 min-idle: 5 max-wait: 60000 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 validation-query: SELECT 1 FROM DUAL validation-query-timeout: 60000 test-on-borrow: false test-on-return: false test-while-idle: true time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 100000 ###监控配置 begin### web-stat-filter: # WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter enabled: true url-pattern: "/*" exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" stat-view-servlet: # StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置 enabled: true url-pattern: "/druid/*" reset-enable: false login-username: admin login-password: 123456 allow: 127.0.0.1 ###监控配置 end### filter: # 配置StatFilter stat: db-type: mysql log-slow-sql: true slow-sql-millis: 5000 # 配置WallFilter wall: enabled: true db-type: mysql config: delete-allow: false drop-table-allow: false globalConfig1: #主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID"; idType: 0 #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断" fieldStrategy: 2 #驼峰下划线转换 dbColumnUnderline: true #刷新mapper 调试神器 refreshMapper: true globalConfig2: #主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID"; idType: 3 #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断" fieldStrategy: 2 #驼峰下划线转换 dbColumnUnderline: true #刷新mapper 调试神器 refreshMapper: true mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:/com/gch/**/*Mapper.xml
3.实现逻辑
在module1新增config、entity、mapper、web包 目录结构如下
这里主要贴一下多数据源的配置
package com.gch.druidmodule1.config; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; import java.sql.SQLException; /** * Created by Administrator on 2018/1/15. */ @Configuration @MapperScan(basePackages = "com.gch.mainmodule.mapper",sqlSessionTemplateRef = "SqlSessionTemplateOne") public class DataSourceOneConfig { @ConfigurationProperties(prefix = "spring.datasource.druid.datasource1") @Bean(name = "datasource1") @Primary public DataSource dataSource1() throws SQLException { return DruidDataSourceBuilder.create().build(); } @Bean(name = "sessionFactory1") @Primary public SqlSessionFactory sqlSessionFactory1(@Qualifier(value = "datasource1") DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "transactionManager1") @Primary public DataSourceTransactionManager dataSourceTransactionManager1(@Qualifier("datasource1") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "SqlSessionTemplateOne") @Primary public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("sessionFactory1") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
module2同理,这里注意一下注解@Primary只能在一个配置文件配置
package com.gch.druidmodule2.config; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; import java.sql.SQLException; /** * Created by Administrator on 2028/2/25. */ @Configuration @MapperScan(basePackages = "com.gch.testmodule1.mapper",sqlSessionTemplateRef = "SqlSessionTemplateTow") public class DataSourceTowConfig { @ConfigurationProperties(prefix = "spring.datasource.druid.datasource2") @Bean(name = "datasource2") public DataSource dataSource2() throws SQLException { return DruidDataSourceBuilder.create().build(); } @Bean(name = "sessionFactory2") public SqlSessionFactory sqlSessionFactory2(@Qualifier(value = "datasource2") DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "transactionManager2") public DataSourceTransactionManager dataSourceTransactionManager2(@Qualifier("datasource2") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "SqlSessionTemplateTow") public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("sessionFactory2") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
4.测试效果
打包启动main模块 建议使用idea插件Maven Helper编译
访问rest接口
每个模块也可以单独启动
在这里注意在main模块的启动方法上需要扫描其他模块的包,不然项目是没法启动的
package com.gch.druidmain; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @SpringBootApplication(scanBasePackages = {"com.gch.druidmain", "com.gch.druidmodule1", "com.gch.druidmodule2"}) public class DruidMainApplication { public static void main(String[] args) { SpringApplication.run(DruidMainApplication.class, args); } }
5.贴上源码地址
https://github.com/guanxiaohe2017/springBoot-druid-mybatisPlus
以上是关于在springBoot框架下使用druid+myBatisPlus实现多数据源(不同模块不同数据源)的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot+ShardingSphereJDBC实现读写分离!
SpringBoot2——数据访问的集成 & 单元测试(JUnit5)
alibaba druid 在springboot start autoconfig 下的bug
SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页
SpringBoot系列七:SpringBoot 集成 MyBatis事物配置及使用druid 数据源druid 监控使用