springboot配置多数据源
首先是一个正常能运行的springboot项目
目前我这的要求是springboot配置了3个数据源(1.本地的mysql,2远程的mysql,3远程的oracle)
第一步:在pom.xml文件中导入依赖
<!--多数据源--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>2.5.6</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.20</version> <!--<version>1.1.21</version>--> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version> </dependency>
第二步:yml文件中加入数据源的配置
server: port: 8989 spring: datasource: dynamic: primary: localhost # 配置默认数据库 datasource: localhost: # 数据源1配置 url: jdbc:mysql://localhost:3306/water_net?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: haili888 driver-class-name: com.mysql.cj.jdbc.Driver weather: # 数据源2配置 url: jdbc:mysql://localhost:3306/sandthief?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 username: root password: haili888 driver-class-name: com.mysql.cj.jdbc.Driver water: # 数据源3配置 driver-class-name: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@10.42.15.19:1521:orcl username: slj password: slj@2018 durid: initial-size: 1 max-active: 20 min-idle: 1 max-wait: 60000 autoconfigure: exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 去除druid配置
第三步:开始使用了,需要哪个数据源,就直接在使用的serviceimp 实现层,添加注解@DS("数据源的名称")
基本上完成了,如果有报错,可能跟
druid-spring-boot-starter这个jar 包的版本有关
菜鸟一枚,有问题希望指出,相互学习,目前我这边测试成功了