参考文章:https://www.cnblogs.com/tswhq/p/11668078.html
话不多说,直入正题:
我这里是为了实现一个业务场景。Spring如何配置多数据源并整合Druid的方式网上已经一大片了。
但是那种方式适应场景是采用主从模式的数据库。
(做法)我们需要事先在配置文件配置好服务需要用到的多个数据源信息,并创建自定义注解,这里注解一般声明在Service层的方法上较为合理。然后不同的Service根据注解的value属性区分方法所用到的数据源
这里,我实现的是在项目运行时,根据参数传递或其他途径获取到数据库连接配置信息,进行动态的连接创建,切换,和销毁
pom依赖:
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Druid 数据源配置:
server:
port: 8080
spring:
profiles:
active: dev
datasource:
druid:
name: druid-default-datasource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/qb?characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: root
initial-size: 5
max-active: 30
min-idle: 5
filter:
stat:
enabled: true
log-slow-sql: true
merge-sql: true
slow-sql-millis: 30000 #单位毫秒
connection-stack-trace-enable: true
config:
enabled: true
slf4j:
enabled: true
query-timeout: 1800
max-wait: 60000
validation-query: select 1 from dual
pool-prepared-statements: true #mysql5.5以上或者oracle建议开启
testWhileIdle: true
filters: stat,wall,config,slf4j
break-after-acquire-failure: true
time-between-eviction-runs-millis: 300000
connection-error-retry-attempts: 3
stat-view-servlet:
enabled: true #默认为tr