SpringBoot使用dynamic-datasource-spring-boot-starter搭建多数据源

参考:(21条消息) 使用dynamic-datasource-spring-boot-starter做多数据源及源码分析_0x2015的博客-CSDN博客_dynamic-datasource-spring-booticon-default.png?t=M276https://blog.csdn.net/w57685321/article/details/106823660

dynamic-datasource-spring-boot-starter 是一个基于springboot的快速集成多数据源的启动器

它和mybatis-plus是一个生态圈里的,很容易集成mybatis-plus

  • maven依赖
         
            org.springframework.boot
            spring-boot-starter-web
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.10
        
        <--mp依赖-->
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.2
        
        <--dynamic多数据源依赖-->
        
            com.baomidou
            dynamic-datasource-spring-boot-starter
            3.4.1
            
                
                    org.springframework.boot
                    spring-boot-starter-jdbc
                
            
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
  •  yaml文件配置
spring:
  datasource:
    dynamic:
      # druid连接池设置
      druid:
        #     配置初始化大小、最小、最大线程数
        initialSize: 5
        minIdle: 5
        #     CPU核数+1,也可以大些但不要超过20,数据库加锁时连接过多性能下降
        maxActive: 20
        #     最大等待时间,内网:800,外网:1200(三次握手1s)
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        #     配置一个连接在池中最大空间时间,单位是毫秒
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1
        testWhileIdle: true
        #     设置从连接池获取连接时是否检查连接有效性,true检查,false不检查
        testOnBorrow: true
        #     设置从连接池归还连接时是否检查连接有效性,true检查,false不检查
        testOnReturn: true
        #     可以支持PSCache(提升写入、查询效率)
        poolPreparedStatements: true
        #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        filters: stat
        #     保持长连接
        keepAlive: true
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      #  dynamic主从设置
      primary: master  #设置默认的数据源或者数据源组,默认值即为master
      strict: false  #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候回抛出异常,不启动会使用默认数据源.
      datasource:
        master:
          url: jdbc:mysql://localhost:3306/hotel?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
          username: root
          password: 123456
          driver-class-name: com.mysql.cj.jdbc.Driver
          type: com.alibaba.druid.pool.DruidDataSource
        slave_1:
          url: jdbc:mysql://82.157.123.73:3306/hotel_team_2?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
          username: admin
          password: 123456
          driver-class-name: com.mysql.cj.jdbc.Driver
          type: com.alibaba.druid.pool.DruidDataSource
mybatis-plus:
  #MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。
  mapper-locations: classpath*:mybatis/*.xml
  #单独的 MyBatis 配置,请将其路径配置到 configLocation 中  注意 configuration与config-location不能一起用
  #config-location: classpath*:mybatis-config.xml
  # 实体对象的扫描包,MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名
  type-aliases-package: com.song.druid.test.domain
  #枚举对象的扫描包
  type-enums-package: com.song.druid.test.domain.enums
  configuration:
    # 禁用缓存
    cache-enabled: false
    #开启映射时驼峰命名
    map-underscore-to-camel-case: true
    #开启控制台 SQL 日志打印
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    auto-mapping-behavior: full
  global-config:
    db-config:
      #全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置
      id-type: auto
      #表名前缀,全局配置后可省略 @TableName()配置。默认值:null
      table-prefix: tb_
  • Druid监控启动页面配置
@Configuration
public class DruidConfig {
    /**
     * 配置Druid 监控启动页面
     *
     * @return servletRegistrationBean
     */
    @Bean
    @ConditionalOnMissingBean
    public ServletRegistrationBean druidStartViewServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // 白名单
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // 黑名单
        servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
        // 登录查看信息的账密,用于登录Druid监控后台
        servletRegistrationBean.addInitParameter("loginUsername", "druid");
        servletRegistrationBean.addInitParameter("loginPassword", "druid");
        // 是否能够重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "true");
        return servletRegistrationBean;
    }

    /**
     * Druid监控过滤器配置规则
     * ConditionalOnMissingBean 防止注册相同的bean
     *
     * @return filterFilterRegistrationBean
     */
    @Bean
    @ConditionalOnMissingBean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterFilterRegistrationBean = new FilterRegistrationBean<>();
        filterFilterRegistrationBean.setFilter(new WebStatFilter());
        // 添加过滤规则
        filterFilterRegistrationBean.addUrlPatterns("/*");
        // 添加不需要忽略的格式信息
        filterFilterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterFilterRegistrationBean;
    }
}
  • 启动类添加注解‘exclude = DruidDataSourceAutoConfigure.class
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
@MapperScan("com.song.druid.test.mapper")
public class DruidTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(DruidTestApplication.class, args);
    }
}
  • 实体类

   master数据源实体类

@Data
@TableName(value = "admin_membership_grade")
public class MembershipGrade implements Serializable {
    private static final long serialVersionUID = 1L;
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;
    private String title;
    private Integer maxOrderCount;
    private Integer maxMoney;
    private Integer deleted;
    private Date createTime;
    private Date updateTime;
}

   slave_1数据源实体类

@Data
@TableName("hotel_answer")
public class Answer implements Serializable {
    private static final long serialVersionUID = 1L;
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;
    private Long questionId;
    private Long userId;
    @TableField(value = "user_identity")
    private Integer identity;
    @TableField(value = "user_nickname")
    private String nickname;
    private String content;
    private Integer deleted;
    private Date createTime;
    private Date updateTime;
}
  • service层里面在想要切换数据源的方法上加上@DS注解就行了,也可以加在整个service层上,方法上的注解优先于类上注解(这里为了方便,之间在controller层测试)
@RestController
@RequestMapping("/grade")
public class MembershipController {
    @Resource
    private MembershipMapper membershipMapper;
    @Resource
    private AnswerMapper answerMapper;

    @GetMapping("/{id}")
    public MembershipGrade getMembershipGrade(@PathVariable("id") Long id){
        return membershipMapper.selectById(id);
    }
    @GetMapping("/answer/{id}")
    @DS("slave_1")
    public Answer getAnswer(@PathVariable("id") Long id){
        return answerMapper.selectById(id);
    }
}
  • 启动项目

访问  http://localhost:8080/druid/login.html  可以看到两个数据源

 SpringBoot使用dynamic-datasource-spring-boot-starter搭建多数据源_第1张图片

测试 http://localhost:8080/grade/3    http://localhost:8080/grade/answer/1

SpringBoot使用dynamic-datasource-spring-boot-starter搭建多数据源_第2张图片

 

 

你可能感兴趣的:(springboot)