mybatis-plus整合alibaba.druid实现多数据源配置

须知:依托于springboot项目实现

一,添加maven依赖

		<!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.46</version>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!--Mybatis-Plus启动器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!-- Mybatis-Plus  多数据源 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>

这些都是必要依赖,springboot的自行添加

二,配置application.yml文件

server:
  port: 8111
spring:
  #autoconfigure: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    dynamic:
      primary: master #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        master:
          url: jdbc:mysql://127.0.0.1:3306/xqd_database?zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
        slave_1:
          url: jdbc:mysql://127.0.0.1:3306/security?zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver
        #  <-------------druid数据源配置--------------------->
        druid:
          filters: stat,wall  #监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall
          validation-query: SELECT 1 FROM DUAL  # 连接是否有效的查询语句
          validation-query-timeout: 60000
          initial-size: 50  #初始化时建立物理连接的个数
          min-idle: 50  #最小连接池数量
          max-active: 100  #最大连接池数量
          test-on-borrow: false  #申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
          test-on-return: false #归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
          time-between-eviction-runs-millis: 60000  # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
          min-evictable-idle-time-millis: 300000  # 配置一个连接在池中最小生存的时间,单位是毫秒
          web-stat-filter:
            exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
          #设置访问druid监控页面的拦截路径及账号和密码
          stat-view-servlet:
            allow:
            login-username: admin
            login-password: admin


mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  typeAliasesPackage: com.mp.entity
  #信息输出设置 日志
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 逻辑删除
  global-config:
    db-config:
      logic-delete-value: 1   #1为删除
      logic-not-delete-value: 0   #0 为没有删除

三,启动类注解配置

在注解中加上这个配置 exclude = DruidDataSourceAutoConfigure.class
因为Spring Boot 框架会自动配置数据源,自动从yml中读取数据源信息,因此我们在配置自定义的数据源的时候,需要exclude = DataSourceAutoConfiguration.class来禁掉数据源的自动配置。

@MapperScan("com.mp.dao")
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class SpringbootMPApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMPApplication.class,args);

    }
}

主要是这三个部分的配置,再往后就是使用的问题,就正常按照mybatis plus的开发过程就可以。
在mapper或者service的类中或方法中可以加入@DS(“slave_1”)或者@DS(“xx”)的注解,来设置指向不同的数据源,不写则是指向默认数据源,方法上的@DS(“xx”)注解优先级高于类上面的。

我也是从网上这种找的,大部分都是这样子,主要是yml中配置正确了,一般没什么问题,我是成功了,赶快记录一下

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,需要在pom.xml中添加依赖,如下: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 然后,需要在application.yml中配置Druid数据Mybatis-plus配置,如下: ```yaml spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 username: root password: root druid: max-active: 20 initial-size: 1 max-wait: 60000 min-idle: 1 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false mybatis-plus: mapper-locations: classpath:/mapper/*.xml global-config: db-config: id-type: auto field-strategy: not_empty table-prefix: t_ logic-delete-value: 1 logic-not-delete-value: 0 configuration: map-underscore-to-camel-case: true ``` 接着,我们需要创建一个数据切换的工具类,如下: ```java public class DynamicDataSourceContextHolder { private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>(); public static void setDataSourceType(String dataSourceType) { CONTEXT_HOLDER.set(dataSourceType); } public static String getDataSourceType() { return CONTEXT_HOLDER.get(); } public static void clearDataSourceType() { CONTEXT_HOLDER.remove(); } } ``` 然后,我们需要创建一个切面,用来在方法执行前切换数据,如下: ```java @Component @Aspect public class DynamicDataSourceAspect { @Pointcut("@annotation(com.example.demo.annotation.DataSource)") public void dataSourcePointCut() {} @Around("dataSourcePointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); DataSource dataSource = signature.getMethod().getAnnotation(DataSource.class); if (dataSource == null) { DynamicDataSourceContextHolder.setDataSourceType("db1"); } else { DynamicDataSourceContextHolder.setDataSourceType(dataSource.value()); } try { return point.proceed(); } finally { DynamicDataSourceContextHolder.clearDataSourceType(); } } } ``` 在需要使用不同数据的方法上,我们可以使用@DataSource注解来指定数据,如下: ```java @DataSource("db2") public List<User> selectUserList() { return userMapper.selectList(null); } ``` 最后,我们需要在配置类中配置多个数据,如下: ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.druid.db1") public DataSource db1() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.druid.db2") public DataSource db2() { return DruidDataSourceBuilder.create().build(); } @Bean @Primary public DataSource dataSource(DataSource db1, DataSource db2) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("db1", db1); targetDataSources.put("db2", db2); DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource(); dataSource.setTargetDataSources(targetDataSources); dataSource.setDefaultTargetDataSource(db1); return dataSource; } } ``` 以上就是Mybatis-plus切换Druid数据的完整代码和配置文件配置。其中,DynamicRoutingDataSource是动态数据实现类,需要自行实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值