SpringBoot 2.X数据库主从配置


本文以MySql为例,介绍SpringBoot2.X相关主从、读写分离配置,话不多说,直接上步骤

1、首先进行

2、添加pom依赖



    com.alibaba
    druid
    1.1.20



    org.apache.shardingsphere
    sharding-jdbc-spring-boot-starter
    4.1.1

3、application.yml添加如下配置

spring:
  shardingsphere:
    datasource:
      names: master,slave
      # 主数据源
      master:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test_db?createDatabaseIfNotExist=true&useSSL=false&serverTimezone=Asia/Shanghai&&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
        username: root
        password: abc123456
        initialSize: 10
        minIdle: 10
        maxActive: 30
      # 从数据源
      slave:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://1localhost2:3306/test_db?createDatabaseIfNotExist=true&useSSL=false&serverTimezone=Asia/Shanghai&&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
        username: root
        password: vbf12345
        initialSize: 10 #连接池初始化连接数
        minIdle: 10  #连接池最小连接数
        maxActive: 30  #连接池最大连接数
    masterslave:
      # 读写分离配置
      load-balance-algorithm-type: round_robin
      # 最终的数据源名称
      name: dataSource
      # 主库数据源名称
      master-data-source-name: master
      # 从库数据源名称列表,多个逗号分隔
      slave-data-source-names: slave
    props:
      # 开启SQL显示,默认false
      sql:
        show: true

4、启动类设置如下注解

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//去掉数据源

5、测试结果如下:读取从库,写入主库