【快速使用ShardingJDBC的哈希分片策略进行分库分表】

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 【快速使用ShardingJDBC的哈希分片策略进行分库分表】


🍊1.引入maven依赖

在pom.xml中添加依赖

<!-- Maven 构建配置 -->
<build>
    <!-- 插件列表 -->
    <plugins>
        <!-- Maven 编译插件 -->
        <plugin>
            <!-- 插件所在 groupId -->
            <groupId>org.apache.maven.plugins</groupId>
            <!-- 插件所在 artifactId -->
            <artifactId>maven-compiler-plugin</artifactId>
            <!-- 插件配置 -->
            <configuration>
                <!-- 源码编译版本 -->
                <source>8</source>
                <!-- 目标编译版本 -->
                <target>8</target>
            </configuration>
        </plugin>
    </plugins>
</build>
<!-- Maven 依赖管理配置 -->
<dependencyManagement>
    <!-- 依赖列表 -->
    <dependencies>
        <!-- Spring Boot 依赖管理 -->
        <dependency>
            <!-- 依赖所在 groupId -->
            <groupId>org.springframework.boot</groupId>
            <!-- 依赖所在 artifactId -->
            <artifactId>spring-boot-dependencies</artifactId>
            <!-- 依赖版本 -->
            <version>2.3.1.RELEASE</version>
            <!-- 依赖类型 -->
            <type>pom</type>
            <!-- 依赖范围 -->
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<!-- 项目依赖列表 -->
<dependencies>
    <!-- 分库分表组件 Sharding JDBC -->
    <dependency>
        <!-- 依赖所在 groupId -->
        <groupId>org.apache.shardingsphere</groupId>
        <!-- 依赖所在 artifactId -->
        <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
        <!-- 依赖版本 -->
        <version>4.1.1</version>
    </dependency>
    <!-- Spring Boot 核心依赖 -->
    <dependency>
        <!-- 依赖所在 groupId -->
        <groupId>org.springframework.boot</groupId>
        <!-- 依赖所在 artifactId -->
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!-- Spring Boot 测试依赖 -->
    <dependency>
        <!-- 依赖所在 groupId -->
        <groupId>org.springframework.boot</groupId>
        <!-- 依赖所在 artifactId -->
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <!-- 数据源连接池组件 Druid -->
    <dependency>
        <!-- 依赖所在 groupId -->
        <groupId>com.alibaba</groupId>
        <!-- 依赖所在 artifactId -->
        <artifactId>druid</artifactId>
        <!-- 依赖版本 -->
        <version>1.1.22</version>
    </dependency>
    <!-- MySQL 驱动依赖 -->
    <dependency>
        <!-- 依赖所在 groupId -->
        <groupId>mysql</groupId>
        <!-- 依赖所在 artifactId -->
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- MyBatis-Plus 集成依赖 -->
    <dependency>
        <!-- 依赖所在 groupId -->
        <groupId>com.baomidou</groupId>
        <!-- 依赖所在 artifactId -->
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <!-- 依赖版本 -->
        <version>3.0.5</version>
    </dependency>
</dependencies>

🍊2.启动类上添加注解@MapperScan

扫描对应的mapper路径

@MapperScan("com.example.shardingDemo.mapper")
@SpringBootApplication
public class ShardingJDBCApplication {
    public static void main(String[] args) {
        SpringApplication.run(ShardingJDBCApplication.class,args);
    }
}

🍊3.添加application.properties配置

# 哈希分片策略分库分表
# 设置数据源名称为 m1
spring.shardingsphere.datasource.names=m1,m2
# 设置数据源类型为 Druid 数据源
spring.shardingsphere.datasource.m1.type=com.alibaba.druid.pool.DruidDataSource
# 设置数据源驱动为 MySQL 的 JDBC 驱动
spring.shardingsphere.datasource.m1.driver-class-name=com.mysql.cj.jdbc.Driver
# 设置数据源连接 URL,连接本地 MySQL 数据库的 userdb 库
spring.shardingsphere.datasource.m1.url=jdbc:mysql://192.168.122.128:3306/masterdemo?serverTimezone=GMT%2B8
# 设置连接数据库所需的用户名和密码
spring.shardingsphere.datasource.m1.username=root
spring.shardingsphere.datasource.m1.password=bfb8f36cc2616995
# 设置数据源名称为 m2
spring.shardingsphere.datasource.m2.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m2.url=jdbc:mysql://192.168.122.128:3306/masterdemo2?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m2.username=root
spring.shardingsphere.datasource.m2.password=bfb8f36cc2616995
# 设置分片表的实际数据节点,对应两个数据表:m1.t_user_1 和 m1.t_user_2
spring.shardingsphere.sharding.tables.user.actual-data-nodes=m$->{1..2}.t_user_$->{1..2}
# 设置分片键为 user_id
spring.shardingsphere.sharding.tables.user.key-generator.column=user_id
# 设置分布式 ID 生成算法为 SNOWFLAKE 算法,worker ID 为 1
spring.shardingsphere.sharding.tables.user.key-generator.type=SNOWFLAKE
# Spring Boot 应用配置项:ShardingSphere 分库分表配置之课程表的主键生成策略配置项,属性名: worker.id,属性值: 1 (表示该应用程序所使用的 Snowflake 算法的工作节点 ID 为 1)
spring.shardingsphere.sharding.tables.user.key-generator.props.worker.id=1
# 设置分表算法为 inline 分片算法,分片列为 user_id,分片规则为课程编号为奇数的记录在 m1.t_user_1 表中,课程编号为偶数的记录在 m1.t_user_2 表中
spring.shardingsphere.sharding.tables.user.table-strategy.inline.sharding-column=user_id
# table-strategy.inline:表示使用内联表达式的分片策略。lgorithm-expression:表示表名生成算法表达式。t_user_$->{user_id%2+1}:表示生成的表名,即t_user_后面接下标为(user_id%2+1)的表。
# user_id是表中的一个自增主键,%2表示对2取余数,+1表示取余结果加1,即user_id值为偶数进入到t_user_1表,user_id值为奇数进入到t_user_2表。
spring.shardingsphere.sharding.tables.user.table-strategy.inline.algorithm-expression=t_user_$->{user_id%2+1}
# 使用 Spring 和 ShardingSphere 进行数据库分片,将 user 表根据 user_id 字段进行分片,数据库策略为 inline,即使用算法表达式进行分片
spring.shardingsphere.sharding.tables.user.database-strategy.inline.sharding-column=user_id
# 用户 ID 对2取余再加1,结果为1或2,根据结果选择数据库 m1 或 m2 进行存储
spring.shardingsphere.sharding.tables.user.database-strategy.inline.algorithm-expression=m$->{user_id%2+1}
# 设置 SQL 显示开启,方便调试
spring.shardingsphere.props.sql.show=true
# 允许覆盖 Bean 定义,用于调试时快速更新配置
spring.main.allow-bean-definition-overriding=true

🍊4.普通的自定义实体类

import lombok.Data;
@Data
public class User {
    private int userId;
    private String userName;
    private String status;
    private int age;
}

🍊5.写个测试类验证一下

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.shardingDemo.entity.Course;
import com.example.shardingDemo.entity.Dict;
import com.example.shardingDemo.entity.User;
import com.example.shardingDemo.mapper.CourseMapper;
import com.example.shardingDemo.mapper.DictMapper;
import com.example.shardingDemo.mapper.UserMapper;
import org.apache.shardingsphere.api.hint.HintManager;
import org.junit.Test;
import org.junit.jupiter.api.Tags;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ShardingJDBCTest {
    @Resource
    CourseMapper courseMapper;
    @Resource
    DictMapper dictMapper;
    @Resource
    UserMapper userMapper;
    @Test
    public void addUser(){
        for(int i = 0 ; i < 10 ; i ++){
            User user = new User();
            user.setUserId(i);
            user.setUserName("张三"+i);
            user.setAge(i);
            user.setStatus("1");
            userMapper.insert(user);
        }
    }
}

🍊6.控制台打印的日志

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.1.RELEASE)
2023-11-08 19:05:14.284  INFO 20848 --- [           main] c.e.a.ShardingJDBCTest                   : Starting ShardingJDBCTest on WIN-20230222ULN with PID 20848 (started by Administrator in E:\WarkSpace\基础篇书籍\第8章\apache-shardingsphere-demo)
2023-11-08 19:05:14.285  INFO 20848 --- [           main] c.e.a.ShardingJDBCTest                   : No active profile set, falling back to default profiles: default
2023-11-08 19:05:14.668  INFO 20848 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'stringToNoneShardingStrategyConfigurationConverter' of type [org.apache.shardingsphere.spring.boot.converter.StringToNoneShardingStrategyConfigurationConverter] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-11-08 19:05:14.675  INFO 20848 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.shardingsphere.sharding-org.apache.shardingsphere.shardingjdbc.spring.boot.sharding.SpringBootShardingRuleConfigurationProperties' of type [org.apache.shardingsphere.shardingjdbc.spring.boot.sharding.SpringBootShardingRuleConfigurationProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-11-08 19:05:14.678  INFO 20848 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.shardingsphere.masterslave-org.apache.shardingsphere.shardingjdbc.spring.boot.masterslave.SpringBootMasterSlaveRuleConfigurationProperties' of type [org.apache.shardingsphere.shardingjdbc.spring.boot.masterslave.SpringBootMasterSlaveRuleConfigurationProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-11-08 19:05:14.680  INFO 20848 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.shardingsphere.encrypt-org.apache.shardingsphere.shardingjdbc.spring.boot.encrypt.SpringBootEncryptRuleConfigurationProperties' of type [org.apache.shardingsphere.shardingjdbc.spring.boot.encrypt.SpringBootEncryptRuleConfigurationProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-11-08 19:05:14.682  INFO 20848 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.shardingsphere.shadow-org.apache.shardingsphere.shardingjdbc.spring.boot.shadow.SpringBootShadowRuleConfigurationProperties' of type [org.apache.shardingsphere.shardingjdbc.spring.boot.shadow.SpringBootShadowRuleConfigurationProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-11-08 19:05:14.685  INFO 20848 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.shardingsphere-org.apache.shardingsphere.shardingjdbc.spring.boot.common.SpringBootPropertiesConfigurationProperties' of type [org.apache.shardingsphere.shardingjdbc.spring.boot.common.SpringBootPropertiesConfigurationProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-11-08 19:05:14.811  INFO 20848 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.apache.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration' of type [org.apache.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration$$EnhancerBySpringCGLIB$$bfc54c27] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2023-11-08 19:05:14.990  INFO 20848 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2023-11-08 19:05:15.410  INFO 20848 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2} inited
2023-11-08 19:05:15.462  INFO 20848 --- [           main] o.a.s.core.log.ConfigurationLogger       : ShardingRuleConfiguration:
tables:
  user:
    actualDataNodes: m$->{1..2}.t_user_$->{1..2}
    databaseStrategy:
      inline:
        algorithmExpression: m$->{user_id%2+1}
        shardingColumn: user_id
    keyGenerator:
      column: user_id
      props:
        worker.id: '1'
      type: SNOWFLAKE
    logicTable: user
    tableStrategy:
      inline:
        algorithmExpression: t_user_$->{user_id%2+1}
        shardingColumn: user_id
2023-11-08 19:05:15.462  INFO 20848 --- [           main] o.a.s.core.log.ConfigurationLogger       : Properties:
sql.show: 'true'
2023-11-08 19:05:15.471  INFO 20848 --- [           main] ShardingSphere-metadata                  : Loading 1 logic tables' meta data.
2023-11-08 19:05:15.520  INFO 20848 --- [           main] ShardingSphere-metadata                  : Meta data load finished, cost 58 milliseconds.
 _ _   |_  _ _|_. ___ _ |    _ 
| | |\/|_)(_| | |_\  |_)||_|_\ 
     /               |         
                        3.0.5 
2023-11-08 19:05:15.618  WARN 20848 --- [           main] c.b.m.core.toolkit.TableInfoHelper       : Warn: Could not find @TableId in Class: com.example.apacheshardingspheredemo.entity.Course.
2023-11-08 19:05:15.687  WARN 20848 --- [           main] c.b.m.core.toolkit.TableInfoHelper       : Warn: Could not find @TableId in Class: com.example.apacheshardingspheredemo.entity.Dict.
2023-11-08 19:05:15.699  WARN 20848 --- [           main] c.b.m.core.toolkit.TableInfoHelper       : Warn: Could not find @TableId in Class: com.example.apacheshardingspheredemo.entity.User.
2023-11-08 19:05:15.786  INFO 20848 --- [           main] c.e.a.ShardingJDBCTest                   : Started ShardingJDBCTest in 1.657 seconds (JVM running for 2.159)
2023-11-08 19:05:16.150  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.150  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@63e70bf9), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@63e70bf9, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[0, 张三0, 1, 0])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[0])])
2023-11-08 19:05:16.150  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m1 ::: INSERT INTO t_user_1  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [0, 张三0, 1, 0]
2023-11-08 19:05:16.171  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.171  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@67dc6b48), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@67dc6b48, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[1, 张三1, 1, 1])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[1])])
2023-11-08 19:05:16.171  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m2 ::: INSERT INTO t_user_2  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [1, 张三1, 1, 1]
2023-11-08 19:05:16.174  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.174  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@11cadb32), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@11cadb32, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[2, 张三2, 1, 2])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[2])])
2023-11-08 19:05:16.174  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m1 ::: INSERT INTO t_user_1  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [2, 张三2, 1, 2]
2023-11-08 19:05:16.177  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.178  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@704c3bdf), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@704c3bdf, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[3, 张三3, 1, 3])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[3])])
2023-11-08 19:05:16.178  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m2 ::: INSERT INTO t_user_2  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [3, 张三3, 1, 3]
2023-11-08 19:05:16.181  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.181  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@605eb072), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@605eb072, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[4, 张三4, 1, 4])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[4])])
2023-11-08 19:05:16.181  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m1 ::: INSERT INTO t_user_1  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [4, 张三4, 1, 4]
2023-11-08 19:05:16.184  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.184  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@43fd77d8), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@43fd77d8, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[5, 张三5, 1, 5])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[5])])
2023-11-08 19:05:16.184  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m2 ::: INSERT INTO t_user_2  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [5, 张三5, 1, 5]
2023-11-08 19:05:16.187  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.187  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@32ba5c65), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@32ba5c65, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[6, 张三6, 1, 6])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[6])])
2023-11-08 19:05:16.187  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m1 ::: INSERT INTO t_user_1  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [6, 张三6, 1, 6]
2023-11-08 19:05:16.191  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.191  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@5d96d434), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@5d96d434, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[7, 张三7, 1, 7])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[7])])
2023-11-08 19:05:16.191  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m2 ::: INSERT INTO t_user_2  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [7, 张三7, 1, 7]
2023-11-08 19:05:16.195  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.195  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@13dd7887), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@13dd7887, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[8, 张三8, 1, 8])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[8])])
2023-11-08 19:05:16.195  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m1 ::: INSERT INTO t_user_1  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [8, 张三8, 1, 8]
2023-11-08 19:05:16.199  INFO 20848 --- [           main] ShardingSphere-SQL                       : Logic SQL: INSERT INTO user  ( user_id,
user_name,
status,
age )  VALUES  ( ?,
?,
?,
? )
2023-11-08 19:05:16.199  INFO 20848 --- [           main] ShardingSphere-SQL                       : SQLStatement: InsertStatementContext(super=CommonSQLStatementContext(sqlStatement=org.apache.shardingsphere.sql.parser.sql.statement.dml.InsertStatement@538aa83f, tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@44de8e00), tablesContext=org.apache.shardingsphere.sql.parser.binder.segment.table.TablesContext@44de8e00, columnNames=[user_id, user_name, status, age], insertValueContexts=[InsertValueContext(parametersCount=4, valueExpressions=[ParameterMarkerExpressionSegment(startIndex=65, stopIndex=65, parameterMarkerIndex=0), ParameterMarkerExpressionSegment(startIndex=68, stopIndex=68, parameterMarkerIndex=1), ParameterMarkerExpressionSegment(startIndex=71, stopIndex=71, parameterMarkerIndex=2), ParameterMarkerExpressionSegment(startIndex=74, stopIndex=74, parameterMarkerIndex=3)], parameters=[9, 张三9, 1, 9])], generatedKeyContext=Optional[GeneratedKeyContext(columnName=user_id, generated=false, generatedValues=[9])])
2023-11-08 19:05:16.199  INFO 20848 --- [           main] ShardingSphere-SQL                       : Actual SQL: m2 ::: INSERT INTO t_user_2  ( user_id,
user_name,
status,
age )  VALUES  (?, ?, ?, ?) ::: [9, 张三9, 1, 9]
2023-11-08 19:05:16.207  INFO 20848 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closing ...
2023-11-08 19:05:16.208  INFO 20848 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closed
2023-11-08 19:05:16.209  INFO 20848 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2} closing ...
2023-11-08 19:05:16.209  INFO 20848 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2} closed
Disconnected from the target VM, address: '127.0.0.1:53866', transport: 'socket'
Process finished with exit code 0

🍊7.观察一下数据库的数据

masterdemo.t_user_1表的数据如图下所示:

可以发现masterdemo库的t_user_1表的user_id都是偶数,masterdemo库的t_user_2表没有数据。

masterdemo2.course_2表的数据如图下所示:

可以发现masterdemo2库的t_user_2表的user_id都是奇数,masterdemo2库的t_user_1表没有数据。

🍊8.maven的setting文件

为了避免部分同学下载依赖包不一致导致maven依赖下载不下来,我这里给上自己的配置文件,代码如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Maven 的配置文件 -->
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0
        http://maven.apache.org/xsd/settings-1.1.0.xsd">
  <!-- 设置本地仓库的路径 -->
  <localRepository>D:\Java\ReMaven</localRepository>
  <!-- 设置镜像 -->
  <mirrors>
    <mirror>
      <id>central</id>
      <url>https://repo1.maven.org/maven2/</url>
      <mirrorOf>*</mirrorOf>
    </mirror>
    <!-- 定义一个镜像 -->
    <!-- <mirror>
      <id>aliyunmaven</id> 
      <name>Alibaba Maven Mirror</name> 
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url> 
      <mirrorOf>central</mirrorOf> 
    </mirror>
  -->
  <mirror>
    <id>aliyunmaven</id><!-- 镜像的id -->
    <mirrorOf>*</mirrorOf><!-- 镜像代理的仓库id,这里将中央仓库的地址替换为阿里云的地址 -->
    <name>阿里云公共仓库</name><!-- 镜像的名称 -->
    <url>https://maven.aliyun.com/repository/public</url><!-- 镜像的地址 -->
  </mirror>
  </mirrors>
  <!-- 设置代理 -->
  <proxies></proxies>
  <!-- 设置私有仓库的认证信息 -->
  <servers></servers>
  <!-- 定义构建时添加的环境参数 -->
  <profiles>
    <!-- 定义一个profile -->
    <profile>
      <id>jdk-1.8</id> <!-- profile的id -->
      <activation> <!-- 激活条件 -->
        <activeByDefault>true</activeByDefault> <!-- 默认激活 -->
        <jdk>1.8</jdk> <!-- 使用的JDK版本 -->
      </activation>
      <properties> <!-- 定义环境变量 -->
        <maven.compiler.source>1.8</maven.compiler.source> <!-- 编译代码的源版本 -->
        <maven.compiler.target>1.8</maven.compiler.target> <!-- 编译代码的目标版本 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 项目源码的编码方式 -->
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- 项目输出的编码方式 -->
        <java.version>1.8</java.version> <!-- 使用的Java版本 -->
      </properties>
    </profile>
  </profiles>
  <!-- 设置默认激活的环境 -->
  <activeProfiles>
    <activeProfile>jdk-1.8</activeProfile> <!-- 默认激活的profile -->
  </activeProfiles>
</settings>


相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
5月前
|
Java Maven 数据库
【快速使用ShardingJDBC的哈希分片策略进行分表】
【快速使用ShardingJDBC的哈希分片策略进行分表】
147 0
|
5月前
|
存储 缓存 NoSQL
软件体系结构 - 数据分片(1)哈希分片
【4月更文挑战第20天】软件体系结构 - 数据分片(1)哈希分片
116 8
|
NoSQL 算法 Redis
Redis集群哈希槽数据分片
Redis 集群有16384个哈希槽,每个key通过CRC16校验后对16384取模来决定放置哪个槽. 集群的每个节点负责一部分hash槽。这种结构很容易添加或者删除节点,并且无论是添加删除或者修改某一个节点,都不会造成集群不可用的状态。
237 0
Redis集群哈希槽数据分片
|
12月前
36MyCat - 分片规则(一致性hash)
36MyCat - 分片规则(一致性hash)
48 0
|
12月前
|
算法
29MyCat - 分片规则(固定分片hash算法)
29MyCat - 分片规则(固定分片hash算法)
45 0
|
SQL 存储 算法
ShardingSphere数据分片
坚持是一件比较难的事,坚持并不是自欺欺人的一种自我麻痹和安慰,也不是做给被人的,我觉得,坚持的本质并没有带着过多的功利主义,如果满是功利主义,那么这个坚持并不会长久,也不会有好的收获,坚持应该带着热爱,带着思想,把它当成习惯,但是并不是内卷,而是一种发自内心的喜欢和平实!希望我们都有自己的坚持,坚持写一篇文章,坚持爱一个人,坚持读一本书,坚持走向远方!
129 0
|
存储 缓存 算法
三种常用的数据分片方式:Hash分片,一致性Hash分片和按照数据范围分片
三种常用的数据分片方式:Hash分片,一致性Hash分片和按照数据范围分片
434 0
三种常用的数据分片方式:Hash分片,一致性Hash分片和按照数据范围分片
|
SQL 存储 算法
sharding-jdbc 分库分表的 4种分片策略,还蛮简单的
sharding-jdbc 分库分表的 4种分片策略,还蛮简单的
1688 0
sharding-jdbc 分库分表的 4种分片策略,还蛮简单的
|
SQL 存储 缓存
聊聊分库分表后非Sharding Key查询的三种方案~(建议收藏)
聊聊分库分表后非Sharding Key查询的三种方案~(建议收藏)
766 0
|
SQL druid 算法
ShardingSphere-Sharding-JDBC水平分表(分片策略) | 学习笔记
快速学习ShardingSphere-Sharding-JDBC水平分表(分片策略)。
603 0
ShardingSphere-Sharding-JDBC水平分表(分片策略) | 学习笔记