springboot项目使用Sharding-JDBC配置读写分离

1、引入Sharding-JDBC依赖

<dependency>
  <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    <version>4.0.0-RC1</version>
</dependency>

2、在yml配置文件中配置主从数据源

spring:
  main:
    allow-bean-definition-overriding: true
  shardingsphere:
    datasource:
      names:
        master,slave
      # 主数据源
      master:
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:8080/db?useUnicode=true
        username: root
        password: 123
        driver-class-name: com.mysql.jdbc.Driver
      # 从数据源
      slave:
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:8081/db?useUnicode=true
        username: root
        password: 123
        driver-class-name: com.mysql.jdbc.Driver
    masterslave:
      # 读写分离配置
      load-balance-algorithm-type: round_robin
      # 最终的数据源名称
      name: dataSource
      # 主库数据源名称
      master-data-source-name: master
      # 从库数据源名称列表,多个逗号分隔
      slave-data-source-names: slave
    props:
      # 开启SQL显示,在控制台可以看见打印的sql语句,默认false
      sql:
        show: true

你可能感兴趣的:(springBoot)