ShardingSphere同时实现分库分表和读写分离,分库分表不生效问题

问题产生的配置,依赖
<sharding-sphere.version>4.0.0-RC1</sharding-sphere.version>

 #这种配置(spring.shardingsphere.masterslave这一层)会导致分库分表的配置不生效,
 masterslave:
   # 配置主从名称,可以任意取名字
   name: ms
   # 配置主库master,负责数据的写入
   master-data-source-name: ds0
   # 配置从库slave节点
   slave-data-source-names: ds1
   # 配置slave节点的负载均衡均衡策略,采用轮询机制
   load-balance-algorithm-type: round_robin

需要更换配置写法

"spring.shardingsphere.sharding.master-slave-rules"下面
      # 这种读写分离配置才能用(读写分离,但是数据库一定要做主从复制)
      master-slave-rules:
        ds0: #数据库分区,此处必须为  shardingsphere.names中列举的数据源
          master-data-source-name: ds0 #ds_0区的主库
          slave-data-source-names: ds1,ds2 #ds_0区的从库
          load-balance-algorithm-type: round_robin

当前POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sharding-jdbc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sharding-jdbc</name>
    <description>sharding-jdbc</description>
    <properties>
        <java.version>1.8</java.version>
        <sharding-sphere.version>4.0.0-RC1</sharding-sphere.version>
    </properties>
    <dependencies>
        <!-- 依赖web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 依赖mybatis和mysql驱动 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
<!--            <version>5.1.47</version>-->
            <scope>runtime</scope>
        </dependency>
        <!--依赖lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--依赖sharding-->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>${sharding-sphere.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-core-common</artifactId>
            <version>${sharding-sphere.version}</version>
        </dependency>
        <!--依赖数据源druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

当前配置

server:
  port: 8085
spring:
  main:
    allow-bean-definition-overriding: true
  shardingsphere:
    # 参数配置,显示sql
    props:
      sql:
        show: true
    # 配置数据源
    datasource:
      # 给每个数据源取别名,下面的ds1,ds2,ds3任意取名字
      names: ds0,ds1,ds2
      # 给master-ds1每个数据源配置数据库连接信息
      ds0:
        # 配置druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://192.168.49.128:3306/db_test01?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
        username: root
        password: 123456
        maxPoolSize: 100
        minPoolSize: 5
      # 配置ds2-slave
      ds1:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://192.168.49.129:3306/db_test01?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
        username: root
        password: 123456
        maxPoolSize: 100
        minPoolSize: 5
      # 配置ds3-slave
      ds2:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://192.168.49.129:3306/db_test01?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
        username: root
        password: 123456
        maxPoolSize: 100
        minPoolSize: 5

    # 配置默认数据源ds1
    sharding:
      # 默认数据源,主要用于写,注意一定要配置读写分离 ,注意:如果不配置,那么就会把三个节点都当做从slave节点,新增,修改和删除会出错。
      default-data-source-name: ds0
      # 配置分表的规则
      tables:
        # ksd_user 逻辑表名
        ksd_user:
          # 数据节点:数据源$->{0..N}.逻辑表名$->{0..N}
          actual-data-nodes: ds0.ksd_user$->{0..1}
          # 拆分库策略,也就是什么样子的数据放入放到哪个数据库中。
#          database-strategy:
#            inline:
#              sharding-column: age    # 分片字段(分片键)
#              algorithm-expression: ds->{age % 2} # 分片算法表达式
          table-strategy:
            inline:
              sharding-column: age    # 分片字段(分片键)
              algorithm-expression: ksd_user$->{age % 2} # 分片算法表达式
      # 这种读写分离配置才能用(读写分离,但是数据库一定要做主从复制)
      master-slave-rules:
        ds0: #数据库分区,此处必须为  shardingsphere.names中列举的数据源
          master-data-source-name: ds0 #ds_0区的主库
          slave-data-source-names: ds1,ds2 #ds_0区的从库
          load-balance-algorithm-type: round_robin


#    #这种配置会导致分库分表的配置不生效,需要在“spring.shardingsphere.masterslave”增加
#    masterslave:
#      # 配置主从名称,可以任意取名字
#      name: ms
#      # 配置主库master,负责数据的写入
#      master-data-source-name: ds0
#      # 配置从库slave节点
#      slave-data-source-names: ds1
#      # 配置slave节点的负载均衡均衡策略,采用轮询机制
#      load-balance-algorithm-type: round_robin

# 整合mybatis的配置XXXXX
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.xuexiangban.shardingjdbc.entity

可以看到:查询,写入都是按照当前的配置策略进行

2024-04-05 15:18:07.029  INFO 11112 --- [nio-8085-exec-8] ShardingSphere-SQL                       : Rule Type: sharding
2024-04-05 15:18:07.029  INFO 11112 --- [nio-8085-exec-8] ShardingSphere-SQL                       : Logic SQL: insert into ksd_user(nickname,password,sex,birthday,age) values(?,?,?,?,?)
2024-04-05 15:18:07.029  INFO 11112 --- [nio-8085-exec-8] ShardingSphere-SQL                       : SQLStatement: InsertStatement(super=DMLStatement(super=AbstractSQLStatement(type=DML, tables=Tables(tables=[Table(name=ksd_user, alias=Optional.absent())]), routeConditions=Conditions(orCondition=OrCondition(andConditions=[AndCondition(conditions=[Condition(column=Column(name=age, tableName=ksd_user), operator=EQUAL, compareOperator=null, positionValueMap={}, positionIndexMap={0=4})])])), encryptConditions=Conditions(orCondition=OrCondition(andConditions=[])), sqlTokens=[TableToken(tableName=ksd_user, quoteCharacter=NONE, schemaNameLength=0), SQLToken(startIndex=20)], parametersIndex=5, logicSQL=insert into ksd_user(nickname,password,sex,birthday,age) values(?,?,?,?,?)), deleteStatement=false, updateTableAlias={}, updateColumnValues={}, whereStartIndex=0, whereStopIndex=0, whereParameterStartIndex=0, whereParameterEndIndex=0), columnNames=[nickname, password, sex, birthday, age], values=[InsertValue(columnValues=[org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@595d7a86, org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@322e6e6c, org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@96c0713, org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@5fbd6bf7, org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@6d06b3cc])])
2024-04-05 15:18:07.029  INFO 11112 --- [nio-8085-exec-8] ShardingSphere-SQL                       : Actual SQL: ds0 ::: **insert into ksd_user0** (nickname, password, sex, birthday, age) VALUES (?, ?, ?, ?, ?) ::: [zhangsan579865212, 1234567, 1, 1988-12-03, 0]
2024-04-05 15:18:10.566  INFO 11112 --- [nio-8085-exec-9] ShardingSphere-SQL                       : Rule Type: sharding
2024-04-05 15:18:10.566  INFO 11112 --- [nio-8085-exec-9] ShardingSphere-SQL                       : Logic SQL: insert into ksd_user(nickname,password,sex,birthday,age) values(?,?,?,?,?)
2024-04-05 15:18:10.566  INFO 11112 --- [nio-8085-exec-9] ShardingSphere-SQL                       : SQLStatement: InsertStatement(super=DMLStatement(super=AbstractSQLStatement(type=DML, tables=Tables(tables=[Table(name=ksd_user, alias=Optional.absent())]), routeConditions=Conditions(orCondition=OrCondition(andConditions=[AndCondition(conditions=[Condition(column=Column(name=age, tableName=ksd_user), operator=EQUAL, compareOperator=null, positionValueMap={}, positionIndexMap={0=4})])])), encryptConditions=Conditions(orCondition=OrCondition(andConditions=[])), sqlTokens=[TableToken(tableName=ksd_user, quoteCharacter=NONE, schemaNameLength=0), SQLToken(startIndex=20)], parametersIndex=5, logicSQL=insert into ksd_user(nickname,password,sex,birthday,age) values(?,?,?,?,?)), deleteStatement=false, updateTableAlias={}, updateColumnValues={}, whereStartIndex=0, whereStopIndex=0, whereParameterStartIndex=0, whereParameterEndIndex=0), columnNames=[nickname, password, sex, birthday, age], values=[InsertValue(columnValues=[org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@595d7a86, org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@322e6e6c, org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@96c0713, org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@5fbd6bf7, org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@6d06b3cc])])
2024-04-05 15:18:10.566  INFO 11112 --- [nio-8085-exec-9] ShardingSphere-SQL                       : Actual SQL: ds0 ::: insert into ksd_user1 (nickname, password, sex, birthday, age) VALUES (?, ?, ?, ?, ?) ::: [zhangsan-1515777454, 1234567, 1, 1988-12-03, 1]


2024-04-05 15:11:01.929  INFO 11112 --- [nio-8085-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-04-05 15:11:01.930  INFO 11112 --- [nio-8085-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2024-04-05 15:11:01.930  INFO 11112 --- [nio-8085-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 0 ms
2024-04-05 15:11:02.493  INFO 11112 --- [nio-8085-exec-1] ShardingSphere-SQL                       : Rule Type: sharding
2024-04-05 15:11:02.494  INFO 11112 --- [nio-8085-exec-1] ShardingSphere-SQL                       : Logic SQL: select * from ksd_user where 1=1 and age = ?
2024-04-05 15:11:02.494  INFO 11112 --- [nio-8085-exec-1] ShardingSphere-SQL                       : SQLStatement: SelectStatement(super=DQLStatement(super=AbstractSQLStatement(type=DQL, tables=Tables(tables=[Table(name=ksd_user, alias=Optional.absent())]), routeConditions=Conditions(orCondition=OrCondition(andConditions=[AndCondition(conditions=[Condition(column=Column(name=age, tableName=ksd_user), operator=EQUAL, compareOperator==, positionValueMap={}, positionIndexMap={0=0})])])), encryptConditions=Conditions(orCondition=OrCondition(andConditions=[])), sqlTokens=[TableToken(tableName=ksd_user, quoteCharacter=NONE, schemaNameLength=0)], parametersIndex=1, logicSQL=select * from ksd_user where 1=1 and age = ?)), containStar=true, firstSelectItemStartIndex=7, selectListStopIndex=7, groupByLastIndex=0, items=[StarSelectItem(owner=Optional.absent())], groupByItems=[], orderByItems=[], limit=null, subqueryStatement=null, subqueryStatements=[], subqueryConditions=[])
2024-04-05 15:11:02.494  INFO 11112 --- [nio-8085-exec-1] ShardingSphere-SQL                       : Actual SQL: ds1 ::: select * from ksd_user0 where 1=1 and age = ? ::: [0]
2024-04-05 15:11:04.459  INFO 11112 --- [nio-8085-exec-2] ShardingSphere-SQL                       : Rule Type: sharding
2024-04-05 15:11:04.459  INFO 11112 --- [nio-8085-exec-2] ShardingSphere-SQL                       : Logic SQL: select * from ksd_user where 1=1 and age = ?
2024-04-05 15:11:04.459  INFO 11112 --- [nio-8085-exec-2] ShardingSphere-SQL                       : SQLStatement: SelectStatement(super=DQLStatement(super=AbstractSQLStatement(type=DQL, tables=Tables(tables=[Table(name=ksd_user, alias=Optional.absent())]), routeConditions=Conditions(orCondition=OrCondition(andConditions=[AndCondition(conditions=[Condition(column=Column(name=age, tableName=ksd_user), operator=EQUAL, compareOperator==, positionValueMap={}, positionIndexMap={0=0})])])), encryptConditions=Conditions(orCondition=OrCondition(andConditions=[])), sqlTokens=[TableToken(tableName=ksd_user, quoteCharacter=NONE, schemaNameLength=0)], parametersIndex=1, logicSQL=select * from ksd_user where 1=1 and age = ?)), containStar=true, firstSelectItemStartIndex=7, selectListStopIndex=7, groupByLastIndex=0, items=[StarSelectItem(owner=Optional.absent())], groupByItems=[], orderByItems=[], limit=null, subqueryStatement=null, subqueryStatements=[], subqueryConditions=[])
2024-04-05 15:11:04.459  INFO 11112 --- [nio-8085-exec-2] ShardingSphere-SQL                       : Actual SQL: ds2 ::: select * from ksd_user0 where 1=1 and age = ? ::: [0]
2024-04-05 15:11:06.884  INFO 11112 --- [nio-8085-exec-3] ShardingSphere-SQL                       : Rule Type: sharding
2024-04-05 15:11:06.884  INFO 11112 --- [nio-8085-exec-3] ShardingSphere-SQL                       : Logic SQL: select * from ksd_user where 1=1 and age = ?
2024-04-05 15:11:06.885  INFO 11112 --- [nio-8085-exec-3] ShardingSphere-SQL                       : SQLStatement: SelectStatement(super=DQLStatement(super=AbstractSQLStatement(type=DQL, tables=Tables(tables=[Table(name=ksd_user, alias=Optional.absent())]), routeConditions=Conditions(orCondition=OrCondition(andConditions=[AndCondition(conditions=[Condition(column=Column(name=age, tableName=ksd_user), operator=EQUAL, compareOperator==, positionValueMap={}, positionIndexMap={0=0})])])), encryptConditions=Conditions(orCondition=OrCondition(andConditions=[])), sqlTokens=[TableToken(tableName=ksd_user, quoteCharacter=NONE, schemaNameLength=0)], parametersIndex=1, logicSQL=select * from ksd_user where 1=1 and age = ?)), containStar=true, firstSelectItemStartIndex=7, selectListStopIndex=7, groupByLastIndex=0, items=[StarSelectItem(owner=Optional.absent())], groupByItems=[], orderByItems=[], limit=null, subqueryStatement=null, subqueryStatements=[], subqueryConditions=[])
2024-04-05 15:11:06.885  INFO 11112 --- [nio-8085-exec-3] ShardingSphere-SQL                       : Actual SQL: ds1 ::: select * from ksd_user0 where 1=1 and age = ? ::: [0]
2024-04-05 15:11:21.776  INFO 11112 --- [nio-8085-exec-4] ShardingSphere-SQL                       : Rule Type: sharding
2024-04-05 15:11:21.776  INFO 11112 --- [nio-8085-exec-4] ShardingSphere-SQL                       : Logic SQL: select * from ksd_user where 1=1 and age = ?
2024-04-05 15:11:21.776  INFO 11112 --- [nio-8085-exec-4] ShardingSphere-SQL                       : SQLStatement: SelectStatement(super=DQLStatement(super=AbstractSQLStatement(type=DQL, tables=Tables(tables=[Table(name=ksd_user, alias=Optional.absent())]), routeConditions=Conditions(orCondition=OrCondition(andConditions=[AndCondition(conditions=[Condition(column=Column(name=age, tableName=ksd_user), operator=EQUAL, compareOperator==, positionValueMap={}, positionIndexMap={0=0})])])), encryptConditions=Conditions(orCondition=OrCondition(andConditions=[])), sqlTokens=[TableToken(tableName=ksd_user, quoteCharacter=NONE, schemaNameLength=0)], parametersIndex=1, logicSQL=select * from ksd_user where 1=1 and age = ?)), containStar=true, firstSelectItemStartIndex=7, selectListStopIndex=7, groupByLastIndex=0, items=[StarSelectItem(owner=Optional.absent())], groupByItems=[], orderByItems=[], limit=null, subqueryStatement=null, subqueryStatements=[], subqueryConditions=[])
2024-04-05 15:11:21.776  INFO 11112 --- [nio-8085-exec-4] ShardingSphere-SQL                       : Actual SQL: ds2 ::: select * from ksd_user0 where 1=1 and age = ? ::: [0]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值