并发量的不断增加,单个数据库承受不了这么大的压力,因此一个项目使用多个数据库也越来越重要,当然使用数据库的模式可能不一样,比如说主从模式、分布式模式。不管是哪种模式都是使用的多数据源。Springboot整合mybatis实现多数据源有两种方式:分包和AOP。这里使用的分包,因为层次更加清晰。
以下代码在评论区会给出github地址。OK,开始整合。
一、环境配置
环境很简单,下面开始整合。
二、代码整合
新建一个Springboot项目名字叫做SpringbootMybatisMutil,开始下面的操作。
第一步:添加依赖
<dependencies>
第二步:修改属性文件
#数据库1的配置
spring.datasource.test1.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test1.jdbc-url = jdbc:mysql://localhost:3306/uav
?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.test1.username = root
spring.datasource.test1.password = root
#数据库2的配置
spring.datasource.test2.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test2.jdbc-url = jdbc:mysql://localhost:3306/uav2
?useUnicode=true&characterEncoding=utf-8&useSSL=false
#上面的这一行在uav后面添加,代码太长我换成了两行,
spring.datasource.test2.username = root
spring.datasource.test2.password = root
#mybatis依赖
mybatis.type-aliases-package = com.fdd.bean
第三步:新建一个bean包,创建Person类
@Mapper
第四步:新建config包,创建DataSourceConfig1l类
@Configuration
再建一个DataSourceConfig2类,里面的代码和DataSourceConfig1的一样,把里面的1换成2即可。
第五步:新建mapper1包,创建PersonMapper类
@Mapper
在这里使用注解的形式进行整合。
第六步:新建mapper2包,创建UserMapper类
@Mapper
内容和PersonMapper是一样的,但是我在测试的时候出现了一些bean重复定义的错误,所以没有使用Person2Mapper这种方法进行命名。
第七步:新建controller包,创建MyController类
@RestController
这里只测试了插入的方法,当然如果你需要service层,自行添加就好了。不过对于基本的增删改查功能,mapper足够。
OK,这个就是多数据源的整合,在我自己的电脑亲测成功。