美文网首页IT必备技能学习架构
spring boot动态切换数据源

spring boot动态切换数据源

作者: 归来_仍是少年 | 来源:发表于2020-12-30 19:08 被阅读0次

    当数据量比较大的时候,我们就需要考虑读写分离了,也就是动态切换数据库连接,对指定的数据库进行操作。在spring中实现动态的切换无非就是利用AOP实现。我们可以使用mybatis-plus作者开发的插件dynamic-datasource-spring-boot-starter。
    demo地址:https://github.com/songshijun1995/spring-boot-dynamic-demo

    1. 新建项目引入依赖
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.1</version>
    </dependency>
    
    1. 配置yml
    server:
      port: 8081
      servlet:
        context-path: /
    
    spring:
      application:
        name: spring-boot-dynamic-demo
      datasource:
        dynamic:
          primary: master #设置默认的数据源或者数据源组,默认值即为master
          strict: false #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源.
          datasource:
            master:  #替换成自己的数据库连接
              url: jdbc:mysql://127.0.0.1:3306/dynamic1?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowMultiQueries=true&rewriteBatchedStatements=true
              username: root
              password: 123456
              driver-class-name: com.mysql.cj.jdbc.Driver
            slave_1:
              url: jdbc:mysql://127.0.0.1:3306/dynamic2?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowMultiQueries=true&rewriteBatchedStatements=true
              username: root
              password: 123456
              driver-class-name: com.mysql.cj.jdbc.Driver
    
    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
      global-config:
        db-config:
          logic-delete-value: 1
          logic-not-delete-value: 0
          logic-delete-field: deleted
      mapper-locations: classpath:/mapper/**.xml
    
    logging:
      level:
        ROOT: INFO
        com.dynamic.dynamicdemo: DEBUG
      pattern:
        file: '%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{50} - %msg%n'
      file:
        name: ${logging.file.path}/${spring.application.name}.log
        path: /home/logs/${spring.application.name}
      logback:
        rollingpolicy:
          max-file-size: 10MB
          max-history: 30
    
    
    1. mybatis-plus和swagger配置我就不多说了,demo里都有
    2. 如何使用
    package com.dynamic.dynamicdemo.service.impl;
    
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.baomidou.mybatisplus.core.toolkit.Wrappers;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.dynamic.dynamicdemo.dto.PageRequest;
    import com.dynamic.dynamicdemo.dto.UserInfoRequest;
    import com.dynamic.dynamicdemo.entities.BaseEntity;
    import com.dynamic.dynamicdemo.entities.UserInfo;
    import com.dynamic.dynamicdemo.mapper.UserInfoMapper;
    import com.dynamic.dynamicdemo.service.UserInfoService;
    import org.springframework.beans.BeanUtils;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    @Service
    public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    
        @DS("master")
        @Transactional(rollbackFor = Exception.class)
        @Override
        public String saveUser(UserInfoRequest request) {
            UserInfo userInfo = new UserInfo();
            BeanUtils.copyProperties(request, userInfo);
            boolean save = save(userInfo);
            if (!save) {
                throw new RuntimeException("添加用户失败");
            }
            return "添加用户成功";
        }
    
        @DS("slave_1")
        @Override
        public IPage<UserInfo> pageUser(PageRequest request) {
            return page(new Page<>(request.getPageNum(), request.getPageSize()), Wrappers.<UserInfo>lambdaQuery().orderByDesc(BaseEntity::getCreateTime));
        }
    }
    

    在方法上或者类上加@DS("master")注解,来指定数据源

    1. 更换为自己的数据库连接,以及建库,运行resources/sql目录下的sql文件
      然后启动项目访问http://127.0.0.1:8081/doc.html进行测试

    相关文章

      网友评论

        本文标题:spring boot动态切换数据源

        本文链接:https://www.haomeiwen.com/subject/smzhoktx.html