zoukankan      html  css  js  c++  java
  • SpringCloud + MyBatis Plus + Druid + dynamic-datasource 多数据源配置

    上下文:

    SpringCloud:Greenwich.SR2

    Spring-boot : 2.1.7.RELEASE

    Spring:5.1.9.RELEASE

    依赖:

    <!--DB start-->
    <!--多数据源依赖-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
        <version>3.2.1</version>
    </dependency>
    <!--mybatis-plus依赖-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.1</version>
    </dependency>
    <!--MySQL依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.2.3</version>
    </dependency>
    
    <!--代码生成start-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.4.1</version>
        <scope>compile</scope>
        <optional>true</optional>
    </dependency>
    <!-- 模板引擎start -->
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.2</version>
        <scope>compile</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.30</version>
        <scope>compile</scope>
        <optional>true</optional>
    </dependency>
    <!-- 模板引擎end -->
    <!--代码生成end-->
    <!--DB end-->

    配置文件application.yml

    spring:
      autoconfigure:
        #自动化配置 例外处理
        exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
      # dynamic-datasource-spring-boot-starter 动态数据源的配置内容
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        dynamic:
          primary: test # 设置默认的数据源或者数据源组,默认值即为 master
          datasource:
            # test 数据源配置
            test:
              url: jdbc:mysql://192.168.1.120:3306/db_test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
              driver-class-name: com.mysql.cj.jdbc.Driver
              username: root
              password: root1234
            # test1 数据源配置
            test1:
              url: jdbc:mysql://192.168.1.120:3306/db_test1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
              driver-class-name: com.mysql.cj.jdbc.Driver
              username: root
              password: root1234
            # test2 数据源配置
            test2:
              url: jdbc:mysql://192.168.1.120:3306/db_test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
              driver-class-name: com.mysql.cj.jdbc.Driver
              username: root
              password: root1234
          #dynamic - 公共配置
          druid:
            initialSize: 5
            minIdle: 5
            maxActive: 30
            maxWait: 60000
            timeBetweenEvictionRunsMillis: 60000
            minEvictableIdleTimeMillis: 300000
            validationQuery: SELECT 'x'
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            poolPreparedStatements: true
            maxPoolPreparedStatementPerConnectionSize: 20
            filters: stat,wall,slf4j,config
            useGlobalDataSourceStat: true
            stat:
              log-slow-sql: true
              merge-sql: true
              slow-sql-millis: 10000
    
    
    mybatis-plus:
      type-aliases-package: com.*
      mapper-locations: classpath*:mapper/*.xml

    如果没有设置上文红色部分配置,请在启动类的 SpringBootApplication 注解上加入过滤配置:

    @SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }

    不加过滤的话,SpringBoo t会自动检测到启动了database模块,会报如下问题:

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/alibaba/druid/spring/boot/autoconfigure/DruidDataSourceAutoConfigure.class]: Invocation of init method failed; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1467)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1431)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1350)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1209)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
        ... 117 common frames omitted
    Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
        at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:233)
        at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineUsername(DataSourceProperties.java:327)
        at com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceWrapper.afterPropertiesSet(DruidDataSourceWrapper.java:40)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
        ... 131 common frames omitted
    2020-11-19 15:34:16.885[main]|INFO|org.eclipse.jetty.server.handler.ContextHandler - Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext@455d04d2{application,/,[file:///C:/Users/Administrator.USER-20190109GW/AppData/Local/Temp/jetty-docbase.2008797717949458032.12394/, jar:file:/D:/Server/maven/repository/io/springfox/springfox-swagger-ui/2.9.2/springfox-swagger-ui-2.9.2.jar!/META-INF/resources],UNAVAILABLE}
    2020-11-19 15:34:16.886[main]|WARN|o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Jetty web server
    2020-11-19 15:34:16.901[main]|INFO|o.s.b.a.l.ConditionEvaluationReportLoggingListener - 
    
    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2020-11-19 15:34:16.905[main]|ERROR|o.s.b.diagnostics.LoggingFailureAnalysisReporter - 
    
    ***************************
    APPLICATION FAILED TO START
    ***************************
    
    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 (no profiles are currently active).
    
    Disconnected from the target VM, address: '127.0.0.1:14992', transport: 'socket'
    
    Process finished with exit code 1

    用法:在service实现层 或者 方法上 添加注解@DS("你的db key"),选定数据源,如:

    @DS("test")
    @Service("userService")
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    }

    PS:

    mybatis plus + druid多数据源(使用dynamic实现)

    Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用

    https://gitee.com/hejr.cn.com/SpringBoot2.0_2019/blob/master/springboot2_004/pom.xml

    https://github.com/baomidou/dynamic-datasource-spring-boot-starter/blob/master/pom.xml

  • 相关阅读:
    风雨20年:我所积累的20条编程经验 (转)
    WPF中的Style(风格,样式)(转)
    WPF入门学习(转)
    关于Viual Studio 改变编辑器背景背景及背景图片(转)
    SSIS 控制流和数据流(转)
    修复 Firefox 下本地使用 Bootstrap 3 时 glyphicon 不显示问题
    .net字符串Gzip压缩和base64string转换:
    .net WebClient发送请求实例:
    XmlDocument解析Soap格式文件案例:
    Xml文件操作的其中一个使用方法:
  • 原文地址:https://www.cnblogs.com/phpdragon/p/14006031.html
Copyright © 2011-2022 走看看