快捷搜索: 王者荣耀 脱发

springboot添加dynamic多数据源+druid数据库连接池

第一步:在pom.xml文件中引入依赖

<!--配置多数据源-->
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
   <version>3.1.1</version>
   <scope>compile</scope>
</dependency>
<!-- 数据连接池 -->
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.22</version>
</dependency>

第二步:在bootstrap.yml文件或application.properties文件中添加配置,我这里的druid就简单的配置了一下,做的全局配置,也可以分别单独给数据源做配置,这里就不做演示了

spring:
  datasource:
    druid:
      stat-view-servlet:
        enabled: true
          # 禁用HTML页面上的“Reset All”功能
        reset-enable: false
          # 登录名
        login-username: admin
          # 登录密码
        login-password: 123456
    dynamic:
      # 全局配置
      druid:
        filters: stat  # 启用内置过滤器(stat必须,否则监控不到SQL)
        # 配置初始化大小、最小、最大
        initial-size: 5 
        min-idle: 5
        keep-alive: true
        #测试连接间隔为55s
        time-between-eviction-runs-millis: 55000
      primary: mysql
      strict: false
      datasource:
        mysql:
          url: jdbc:mysql://ip:3306/users?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
          username: admin
          password: 123456
          driver-class-name: com.mysql.cj.jdbc.Driver
        oracle:
          username: admin
          password: 123
          url: jdbc:oracle:thin:@192.112.50.42:1521:test
          driver-class-name: oracle.jdbc.driver.OracleDriver

第三步:这个很关键,需要在启动类中配置

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)

否则会报以下异常:

Description:

Failed to configure a DataSource: url attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following: If you want an embedded database (H2, HSQL or Derby), please put it on the classpath. If you have database settings to be loaded from a particular profile you may need to activate it (the profiles dev are currently active).

经验分享 程序员 微信小程序 职场和发展