数据库中间件

Jingxc大约 14 分钟java后端java后端MysqlSharing-Shpere

数据库中间件

Apache ShardingSphere 是一款分布式的数据库生态系统,可以将任意数据库转换为分布式数据库,并通过数据分片、弹性伸缩、加密等能力对原有数据库进行增强。

具体使用请参阅中文官网open in new window

Apache ShardingSphere 由 ShardingSphere-JDBC 和 ShardingSphere-Proxy 这 2 款既能够独立部署,又支持混合部署配合使用的产品组成。

ShardingSphere-JDBCShardingSphere-Proxy
数据库任意MySQL/PostgreSQL
连接消耗数
异构语言Java
性能损耗低损耗略高
无中心化
静态入口

还是本分区惯例,旨在快速集成,如需了解概念性知识点,请查阅分区知识点

Maven依赖

这个版本变动很大,不同的版本的配置参数有些不同,版本升级的话可能会遇到各种错误 这里先不贴出maven的依赖了,继续向下看,后面会做详细说明,不同的版本配置不相同,稍微动一下就可能出现很多错误,所以后续会把不同的版本可能遇到的问题全部贴一下

重要

配置简单,出错也很容易,版本,配置

数据分片

配置数据分片规则:

rules:
  sharding:
    tables: # 数据分片规则配置
      t_order: # 逻辑表名称(也就是想要分片的表名)
        # 数据节点:数据源$->{0..N}.逻辑表名$->{0..N}
        actualDataNodes: ds$->{0..1}.t_order$->{0..1} # 由数据源名 + 表名组成(参考 Inline 语法规则)
        # 拆分库策略,也就是什么样子的数据放入放到哪个数据库中。standard,complex,hint,none只能选其中一个
        databaseStrategy: # 分库策略,缺省表示使用默认分库策略,以下的分片策略只能选其一
          standard: # 用于单分片键的标准分片场景
            shardingColumn: id    # 分片字段(分片键)# 分片列名称
            shardingAlgorithmName: database-inline # 分片算法名称,这个名称需要对应配置sharding-algorithms.database-inline,算法名称可随意定义,这个会有问题,后续说明
          complex: # 用于多分片键的复合分片场景
            shardingColumns: # 分片列名称,多个列以逗号分隔
            shardingAlgorithmName: # 分片算法名称
          hint: # Hint 分片策略
            shardingAlgorithmName: # 分片算法名称
          none: # 不分片
        tableStrategy: # 分表策略,同分库策略
        keyGenerateStrategy: # 分布式序列策略
          column: # 自增列名称,缺省表示不使用自增主键生成器
          keyGeneratorName: # 分布式序列算法名称
        auditStrategy: # 分片审计策略
          auditorNames: # 分片审计算法名称
            - <auditor_name>
            - <auditor_name>
          allowHintDisable: true # 是否禁用分片审计hint

警告

shardingAlgorithmName: database-inline这个参数可以出现问题,后续说明

配置默认分裤规则

#可不配置
default-database-strategy:
  none: 

配置默认分表规则

#可不配置
default-sharding-column: # 默认分片列名称,可不配置
default-database-strategy:
  none: #可不配置

绑定表,避免出现避免JOIN 笛卡尔积

在关联查询的时候,有可能出现多条交错的查询

select a.id,a.order_id from t_order_0 a inner join t_order_info b on a.order_id = b.order_id where ...

select a.id,a.order_id from t_order_1 a inner join t_order_info b on a.order_id = b.order_id where ...

为了避免上述现象可以添加绑定表

binding-tables: 
  - t_order,t_order_info

广播表配置 广播的特点是所有的接收端就能收到。所以对于这里的广播表的概念就是插入数据所有的节点都能获取到同样的数据;

一般用到比如数据字典等数据量不到,但是所有数据源都需要有相同的数据的场景

一个表配置成广播表是一定不分片的

插入时,向所有数据源广播发送sql语句

查询时,只查询其中的一个数据源

broadcastTables:
  - t_config

提示

对于用户的登陆表之类的数据量比较大的表而且信息还需要长时间保存完整可采用下面配置,需要注意一下多个参数分表与一个参数分表有些不同

t_log:
  actual-data-nodes: ds$->{0..1}.t_log_$->{2020..2021}_$->{1..12}_$->{1..31}

重点介绍(版本配置)

低版本4.0.0-RC1

这个是最简单的,不用修改代码本身的逻辑,也不用修改代码本身的maven依赖,只需要引入一个新的maven依赖和配置一下配置文件即可

提示

  • 添加maven依赖
  • 添加ymal配置

所有的其他的相关的配置均不需要修改,博主本身用到的相关配置这里介绍一下

数据库驱动

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.47</version>
</dependency>

连接池

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid-spring-boot-starter</artifactId>
  <version>1.1.16</version>
</dependency>

Mybatis-Plus

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.1.2</version>
</dependency>

Spring Boot

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-dependencies</artifactId>
  <version>2.3.2.RELEASE</version>
  <type>pom</type>
  <scope>import</scope>
</dependency>

数据库库和表(通用,后续不做重复介绍)

show databases;

test_demo_0
test_demo_1

use test_demo_0;
SHOW TABLES;

t_order_0
t_order_1

CREATE TABLE `t_order_0` (
  `id` bigint(20) NOT NULL,
  `order_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

实体类(通用,后续不做重复介绍)

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("t_order")
public class OrderInfo {

    @TableId
    private long id;
    private int orderId;
}

提示

@TableName("t_order")和分片时候的表名一致,

如果不加该注解也可以将类名与分片表名一致:例t_order==TOrder

maven依赖(新增):

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

yaml配置,可以直接新建application-low.yml,直接按照下面示例配置即可

spring:
  main:
    allow-bean-definition-overriding: true  #一个实体类对应多张表,覆盖,不然启动报错
  sharding-sphere: # Sharding-JDBC的配置
    datasource:
      # 数据源(逻辑名字)# 给每个数据源取别名,下面的ds0,ds1任意取名字
      names: ds0,ds1
      # 配置数据源# 每个数据源配置数据库连接信息
      ds0:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test_demo_0?characterEncoding=utf8&useSSL=true&createDatabaseIfNotExist=true&serverTimezone=GMT&nullNamePatternMatchesAll=true
        username: root
        password: 100uu100UU
        druid:
          max-active: 3000
          filters: stat
          initialSize: 10
          maxWait: 60000
          minIdle: 10
          timeBetweenEvictionRunsMillis: 60000
          minEvictableIdleTimeMillis: 300000
          validationQuery: select 'x'
          testWhileIdle: true
          testOnBorrow: true
          testOnReturn: false
          poolPreparedStatements: true
          maxOpenPreparedStatements: 20
      ds1:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/test_demo_1?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
        username: root
        password: 100uu100UU
        druid:
          max-active: 3000
          filters: stat
          initialSize: 10
          maxWait: 60000
          minIdle: 10
          timeBetweenEvictionRunsMillis: 60000
          minEvictableIdleTimeMillis: 300000
          validationQuery: select 'x'
          testWhileIdle: true
          testOnBorrow: true
          testOnReturn: false
          poolPreparedStatements: true
          maxOpenPreparedStatements: 20
    # 分片的配置
    sharding:
      # 表的分片策略
      tables:
        # 逻辑表的名称,# t_order 逻辑表名,数据库中需要分表操作的表名,如果不需要做分表操作,走default-table-strategy:
        t_order:
          # 数据节点配置,采用Groovy表达式,数据源$->{0..N}.逻辑表名$->{0..N}
          actual-data-nodes: ds$->{0..1}.t_order_$->{0..1}
          # 配置策略
          table-strategy:
            # 精确匹配
            inline:
              sharding-column: order_id
              algorithm-expression: t_order_$->{order_id % 2}
          database-strategy:
            # 精确匹配
            inline:
              sharding-column: id
              algorithm-expression: ds$->{id % 2}
          # 主键生成策略
          key-generator:
            # 主键
            column: id
            # 雪花算法
            type: SNOWFLAKE
    props: # 日志显示具体的SQL
      sql:
        show: true

直接将主配置文件修改启用文件即可 例(后续通用):

server:
  port: 8089
  servlet:
    context-path: /jingxc/sharding/sphere
spring:
  profiles:
    active: low
  application:
    name: jingxc-boot-sharding-sphere
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml

4.0.0-RC1到这就配置完成,与原有项目能很快融入使用

警告

如果启动报错

Description:

The bean 'dataSource', defined in class path resource [org/apache/shardingsphere/shardingjdbc/spring/boot/SpringBootConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [com/alibaba/druid/spring/boot/autoconfigure/DruidDataSourceAutoConfigure.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

按照提示添加

spring:
  main:
    allow-bean-definition-overriding: true  #一个实体类对应多张表,覆盖,不然启动报错

暂没遇到其他错误

升级4.1.1

maven依赖(新增):

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

警告

启动报错

Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

这是连接池的版本依赖问题,

不要使用druid-spring-boot-starter这个依赖

解决方案 去掉druid-spring-boot-starter这个Spring Boot的依赖,使用单独的链接池

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.2.8</version>
</dependency>

升级5.1.1

4.X和5.X的maven依赖不一样了,配置也做了改动,首先maven依赖不再是之前的artifactId

maven依赖

<!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/shardingsphere-jdbc-core-spring-boot-starter -->
<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
    <version>5.1.1</version>
</dependency>

警告

启动报错

Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSource' defined in class path resource [org/apache/shardingsphere/spring/boot/ShardingSphereAutoConfiguration.class]: Unsatisfied dependency expressed through method 'dataSource' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.shardingsphere.infra.config.mode.ModeConfiguration' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

这是由于配置文件的配置有关

在sharding前加rules:
sharding:整体后移 其他均不变

# 分片的配置
spring:
  sharding-sphere: # Sharding-JDBC的配置
    rules:
      sharding:
        # 表的分片策略
        tables:
          # 逻辑表的名称,# t_order 逻辑表名,数据库中需要分表操作的表名,如果不需要做分表操作,走default-table-strategy:
          t_order:

警告

执行sql语句报错

Cause: java.lang.IllegalStateException: Insert statement does not support sharding table routing to multiple data nodes.] with root cause

这个是由于分片的时候规则有问题 需要使用sharding-algorithms:

也就是说需要单独设置分片规则 改动地方较大,这里直接展出最后结果

spring:
  shardingsphere:
    # 是否开启
    datasource:
      # 数据源(逻辑名字)
      names: m0,m1
      # 配置数据源
      m0:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test_demo_0?useSSL=false&autoReconnect=true&characterEncoding=UTF-8&serverTimezone=UTC
        username: root
        password: 100uu100UU
        druid:
          max-active: 3000
          filters: stat
          initialSize: 10
          maxWait: 60000
          minIdle: 10
          timeBetweenEvictionRunsMillis: 60000
          minEvictableIdleTimeMillis: 300000
          validationQuery: select 'x'
          testWhileIdle: true
          testOnBorrow: true
          testOnReturn: false
          poolPreparedStatements: true
          maxOpenPreparedStatements: 20
      m1:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test_demo_1?useSSL=false&autoReconnect=true&characterEncoding=UTF-8&serverTimezone=UTC
        username: root
        password: 100uu100UU
        druid:
          max-active: 3000
          filters: stat
          initialSize: 10
          maxWait: 60000
          minIdle: 10
          timeBetweenEvictionRunsMillis: 60000
          minEvictableIdleTimeMillis: 300000
          validationQuery: select 'x'
          testWhileIdle: true
          testOnBorrow: true
          testOnReturn: false
          poolPreparedStatements: true
          maxOpenPreparedStatements: 20
    # 分片的配置
    rules:
      sharding:
        # 表的分片策略
        tables:
          # 逻辑表的名称
          t_order:
            # 数据节点配置,采用Groovy表达式
            actual-data-nodes: m${0..1}.t_order_$->{0..1}
            # 配置策略
            table-strategy:
              # 用于单分片键的标准分片场景
              standard:
                sharding-column: order_id
                # 分片算法名字
                sharding-algorithm-name: t-order
            key-generate-strategy: # 主键生成策略
              column: id  # 主键列
              key-generator-name: snowflake  # 策略算法名称(推荐使用雪花算法)
        defaultDatabaseStrategy:
          standard:
            shardingColumn: id
            shardingAlgorithmName: database-inline
        key-generators:
          snowflake:
            type: SNOWFLAKE
        sharding-algorithms:
          database-inline:
            type: INLINE
            props:
              algorithm-expression: m$->{id % 2}
          t-order:
            type: INLINE
            props:
              algorithm-expression: t_order_$->{order_id % 2}
    props:
      # 日志显示具体的SQL
      sql-show: true

设置的时候需要注意如果出现

警告

org.apache.shardingsphere.spi.exception.ServiceProviderNotFoundException: No implementation class load from SPI org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm with type null.

这个是配置的空格有问题,导致启动的时候出现某些参数为空,仔细检查空格,yml就是有这一点不好

如果出现

警告

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.apache.shardingsphere.spring.boot.ShardingSphereAutoConfiguration': Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/apache/tomcat/dbcp/dbcp2/BasicDataSource

注意

网上有说需要加

<dependency>
  <groupId>org.apache.tomcat</groupId>
  <artifactId>tomcat-dbcp</artifactId>
  <version>10.0.16</version>
</dependency>

这里确实可以解决上面那个报错,但这不是主要问题,根源不在这,先加上这个依赖试一下

出现报错:

警告

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shardingSphereDataSource' defined in class path resource [org/apache/shardingsphere/spring/boot/ShardingSphereAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'shardingSphereDataSource' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shardingRuleConfiguration' defined in class path resource [org/apache/shardingsphere/sharding/spring/boot/ShardingRuleSpringBootConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.shardingsphere.infra.config.RuleConfiguration]: Factory method 'shardingRuleConfiguration' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'table_inline': Initialization of bean failed; nested exception is java.lang.IllegalStateException: Inline sharding algorithm expression cannot be null or empty.

table_inline这是分片名称,和上面t-order是一个东西,这个可以《随便》定义

提示

这个就是由于下划线引起的,去掉下划线或者改成中华线即可

例:table-inline

警告

如果运行出现

Parameter index out of range (1 > number of parameters, which is 0).; nested exception is java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).] with root cause

或者 SQL: INSERT INTO t_order ( id, order_no, user_id, amount ) VALUES ( ?, ?, ?, ? )

Cause: java.sql.SQLSyntaxErrorException: Table 'test_demo_0.t_order' doesn't exist

那一定是配置有问题,和依赖没多大关系

  • 检查空格
  • 检查字段名称
  • 检查实体类

空格好好检查

字段需要注意:

rules:
  sharding:
    # 表的分片策略
    tables:
      # 逻辑表的名称,注意注意再注意
      t_order:
        # 数据节点配置,采用Groovy表达式,注意注意再注意
        actual-data-nodes: m${0..1}.t_order_$->{0..1}


sharding-algorithms:
  database-inline:
    type: INLINE
    props:
      algorithm-expression: m$->{id % 2}
  table-inline:
    type: INLINE
    props:
      # 注意注意再注意
      algorithm-expression: t_order_$->{order_id % 2}

实体类检查

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("t_order")
//要不添加@TableName注解,要不注意类名,注意注意再注意
public class OrderInfo {

    @TableId
    private long id;
    private int orderId;
}

暂时还没发现其他问题,如果按照上面的都走了一遍没啥问题,就可以去掉tomcat-dbcp这个依赖了

升级5.2.1

警告

如果出现

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

org.apache.shardingsphere.infra.util.yaml.constructor.ShardingSphereYamlConstructor$1.<init>(ShardingSphereYamlConstructor.java:44)

The following method did not exist:

'void org.apache.shardingsphere.infra.util.yaml.constructor.ShardingSphereYamlConstructor$1.setCodePointLimit(int)'

The calling methods class, org.apache.shardingsphere.infra.util.yaml.constructor.ShardingSphereYamlConstructor$1, was loaded from the following location:

snakeyaml的版本冲突,使用的版本中LoaderOptions没有setCodePointLimit这个方法. 使用的springboot的依赖的版本低了,显式依赖1.33.0即可或高版本即可.

<dependency>
  <groupId>org.yaml</groupId>
  <artifactId>snakeyaml</artifactId>
  <version>1.33</version>
</dependency>

不一定最新的就是最好的,酌情使用,这个已经超过使用的springboot的版本了,还是要考虑

读写分离

sharding-sphere只是实现了读写分离,主从同步不由它来实现

rules:
- !READWRITE_SPLITTING
  dataSources:
    <data_source_name> (+): # 读写分离逻辑数据源名称
       write_data_source_name: # 写库数据源名称
       read_data_source_names: # 读库数据源名称,多个从数据源用逗号分隔
       transactionalReadQueryStrategy (?): # 事务内读请求的路由策略,可选值:PRIMARY(路由至主库)、FIXED(同一事务内路由至固定数据源)、DYNAMIC(同一事务内路由至非固定数据源)。默认值:DYNAMIC
       loadBalancerName: # 负载均衡算法名称
  
  # 负载均衡算法配置
  loadBalancers:
    <load_balancer_name> (+): # 负载均衡算法名称
      type: # 负载均衡算法类型
      props: # 负载均衡算法属性配置
        # ...

maven版本5.2.1

按照数据分片的maven配置即可

yml配置也较为简单,新建application-rw.yml

spring:
  shardingsphere:
    # 是否开启
    datasource:
      # 数据源(逻辑名字)
      names: master,slave
      # 配置数据源
      master:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test_demo_master?useSSL=false&autoReconnect=true&characterEncoding=UTF-8&serverTimezone=UTC
        username: root
        password: 100uu100UU
        druid:
          max-active: 3000
          filters: stat
          initialSize: 10
          maxWait: 60000
          minIdle: 10
          timeBetweenEvictionRunsMillis: 60000
          minEvictableIdleTimeMillis: 300000
          validationQuery: select 'x'
          testWhileIdle: true
          testOnBorrow: true
          testOnReturn: false
          poolPreparedStatements: true
          maxOpenPreparedStatements: 20
      slave:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test_demo_slave?useSSL=false&autoReconnect=true&characterEncoding=UTF-8&serverTimezone=UTC
        username: root
        password: 100uu100UU
        druid:
          max-active: 3000
          filters: stat
          initialSize: 10
          maxWait: 60000
          minIdle: 10
          timeBetweenEvictionRunsMillis: 60000
          minEvictableIdleTimeMillis: 300000
          validationQuery: select 'x'
          testWhileIdle: true
          testOnBorrow: true
          testOnReturn: false
          poolPreparedStatements: true
          maxOpenPreparedStatements: 20
    # 分片的配置
    rules:
      readwrite-splitting:
        data-sources:
          rw: #逻辑哭可自行命名
            static-strategy:
              write-data-source-name: master
              read-data-source-names:
                - slave
            load-balancer-name: round-robin
            transactionalReadQueryStrategy: PRIMARY
        load-balancers:
          round-robin:
            # 负载均衡策略类型,ROUND_ROBIN,RANDOM,WEIGHT,TRANSACTION_RANDOM
            type: ROUND_ROBIN
    props:
      # 日志显示具体的SQL
      sql-show: true

数据库

show databases;

test_demo_master
test_demo_slave

show tables;

t_order

maven版本5.1.1

上述配置yml如果直接拿来用的话会报错

警告

Factory method 'shardingSphereDataSource' threw exception; nested exception is java.lang.NullPointerException

这是由于配置不对,导致无法读取数据源文件

修改配置

rw:
  type: Static
  props:
    write-data-source-name: master
    read-data-source-names: slave

完整配置

spring:
  shardingsphere:
    # 是否开启
    datasource:
      # 数据源(逻辑名字)
      names: master,slave
      # 配置数据源
      master:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test_demo_master?useSSL=false&autoReconnect=true&characterEncoding=UTF-8&serverTimezone=UTC
        username: root
        password: 100uu100UU
        druid:
          max-active: 3000
          filters: stat
          initialSize: 10
          maxWait: 60000
          minIdle: 10
          timeBetweenEvictionRunsMillis: 60000
          minEvictableIdleTimeMillis: 300000
          validationQuery: select 'x'
          testWhileIdle: true
          testOnBorrow: true
          testOnReturn: false
          poolPreparedStatements: true
          maxOpenPreparedStatements: 20
      slave:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test_demo_slave?useSSL=false&autoReconnect=true&characterEncoding=UTF-8&serverTimezone=UTC
        username: root
        password: 100uu100UU
        druid:
          max-active: 3000
          filters: stat
          initialSize: 10
          maxWait: 60000
          minIdle: 10
          timeBetweenEvictionRunsMillis: 60000
          minEvictableIdleTimeMillis: 300000
          validationQuery: select 'x'
          testWhileIdle: true
          testOnBorrow: true
          testOnReturn: false
          poolPreparedStatements: true
          maxOpenPreparedStatements: 20
    # 分片的配置
    rules:
      readwrite-splitting:
        data-sources:
          rw:
            type: Static
            props:
              write-data-source-name: master
              read-data-source-names: slave
            load-balancer-name: round-robin
            transactionalReadQueryStrategy: PRIMARY
        load-balancers:
          round-robin:
            type: ROUND_ROBIN
    props:
      # 日志显示具体的SQL
      sql-show: true

总结

总的来说Sharding-Shpere配置不难,难的是由于配置很容易写错,版本不一致导致配置也不近相同,所以在此梳理一下,如果自己是在不知道哪里错了,可到我的主页找下载代码open in new window

上次编辑于:
贡献者: Jingxc