Sharding-JDBC之垂直分库水平分表

news2024/10/8 17:17:55

目录

    • 一、简介
    • 二、maven依赖
    • 三、数据库
      • 3.1、创建数据库
      • 3.2、订单表
      • 3.3、用户表
    • 四、配置(二选一)
      • 4.1、properties配置
      • 4.2、yml配置
    • 五、实现
      • 5.1、实体
      • 5.2、持久层
      • 5.3、服务层
      • 5.4、测试类
        • 5.4.1、保存订单数据
        • 5.4.2、查询订单数据
        • 5.4.3、保存用户数据
        • 5.4.4、查询用户数据

一、简介

  这里的垂直分库分表是指 垂直分库 + 水平分表 ,怎么解释呢,一般是一个库中同时有订单表和用户表,随着数据增多,就把订单表和用户表单独变成两个库,达到专库专用。当订单库或用户库数据增多,然后分别对订单库和用户库的进行水平分表,一个库多个一样的表。先看下大致架构图:
在这里插入图片描述
数据流向图如下:
在这里插入图片描述

二、maven依赖

pom.xml

<?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.6.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.alian</groupId>
    <artifactId>sharding-jdbc-vertical-database</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sharding-jdbc-vertical-database</name>
    <description>sharding-jdbc-vertical-database</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

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

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  有些小伙伴的 druid 可能用的是 druid-spring-boot-starter

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

  然后出现可能使用不了的各种问题,这个时候你只需要在主类上添加 @SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class}) 即可

package com.alian.shardingjdbc;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})
@SpringBootApplication
public class ShardingJdbcApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShardingJdbcApplication.class, args);
    }

}

三、数据库

3.1、创建数据库

CREATE DATABASE `sharding_3` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE DATABASE `sharding_4` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

3.2、订单表

  在数据库sharding_3创建两张表:tb_order_1tb_order_2,表的结构都是一样的。

tb_order_1

CREATE TABLE `tb_order_1` (
  `order_id` bigint(20) NOT NULL COMMENT '主键',
  `user_id` int unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
  `price` int unsigned NOT NULL DEFAULT '0' COMMENT '价格(单位:分)',
  `order_status` tinyint unsigned NOT NULL DEFAULT '1' COMMENT '订单状态(1:待付款,2:已付款,3:已取消)',
  `order_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `title` varchar(100)  NOT NULL DEFAULT '' COMMENT '订单标题',
  PRIMARY KEY (`order_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_order_time` (`order_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表';

tb_order_2

CREATE TABLE `tb_order_2` (
  `order_id` bigint(20) NOT NULL COMMENT '主键',
  `user_id` int unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
  `price` int unsigned NOT NULL DEFAULT '0' COMMENT '价格(单位:分)',
  `order_status` tinyint unsigned NOT NULL DEFAULT '1' COMMENT '订单状态(1:待付款,2:已付款,3:已取消)',
  `order_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `title` varchar(100)  NOT NULL DEFAULT '' COMMENT '订单标题',
  PRIMARY KEY (`order_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_order_time` (`order_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表';

3.3、用户表

  在数据库sharding_4创建两张表:tb_user_1tb_user_2,表的结构都是一样的。

CREATE TABLE `tb_user_1` (
  `id` bigint(20) NOT NULL COMMENT '主键',
  `user_name` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '用户姓名',
  `age` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '年龄',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
CREATE TABLE `tb_user_2` (
  `id` bigint(20) NOT NULL COMMENT '主键',
  `user_name` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '用户姓名',
  `age` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '年龄',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';

四、配置(二选一)

4.1、properties配置

application.properties

server.port=8899
server.servlet.context-path=/sharding-jdbc

# 允许定义相同的bean对象去覆盖原有的
spring.main.allow-bean-definition-overriding=true
# 数据源名称,多数据源以逗号分隔
spring.shardingsphere.datasource.names=ds1,ds2
# sharding_1数据库连接池类名称
spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource
# sharding_1数据库驱动类名
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
# sharding_1数据库url连接
spring.shardingsphere.datasource.ds1.url=jdbc:mysql://192.168.19.129:3306/sharding_3?serverTimezone=GMT%2B8&characterEncoding=utf8&useUnicode=true&useSSL=false&zeroDateTimeBehavior=CONVERT_TO_NULL&autoReconnect=true&allowMultiQueries=true&failOverReadOnly=false&connectTimeout=6000&maxReconnects=5
# sharding_1数据库用户名
spring.shardingsphere.datasource.ds1.username=alian
# sharding_1数据库密码
spring.shardingsphere.datasource.ds1.password=123456

# sharding_2数据库连接池类名称
spring.shardingsphere.datasource.ds2.type=com.alibaba.druid.pool.DruidDataSource
# sharding_2数据库驱动类名
spring.shardingsphere.datasource.ds2.driver-class-name=com.mysql.cj.jdbc.Driver
# sharding_2数据库url连接
spring.shardingsphere.datasource.ds2.url=jdbc:mysql://192.168.19.130:3306/sharding_4?serverTimezone=GMT%2B8&characterEncoding=utf8&useUnicode=true&useSSL=false&zeroDateTimeBehavior=CONVERT_TO_NULL&autoReconnect=true&allowMultiQueries=true&failOverReadOnly=false&connectTimeout=6000&maxReconnects=5
# sharding_2数据库用户名
spring.shardingsphere.datasource.ds2.username=alian
# sharding_2数据库密码
spring.shardingsphere.datasource.ds2.password=123456

# 指定tb_order表的数据分布情况,配置数据节点,使用Groovy的表达式,逻辑表tb_order对应的节点是:ds1.tb_order_1, ds1.tb_order_2
spring.shardingsphere.sharding.tables.tb_order.actual-data-nodes=ds1.tb_order_$->{1..2}
# 采用行表达式分片策略:InlineShardingStrategy
# 指定tb_order表的分片策略中的分片键
spring.shardingsphere.sharding.tables.tb_order.table-strategy.inline.sharding-column=order_id
# 指定tb_order表的分片策略中的分片算法表达式,使用Groovy的表达式
spring.shardingsphere.sharding.tables.tb_order.table-strategy.inline.algorithm-expression=tb_order_$->{order_id%2==0?2:1}
# 指定tb_order表的主键为order_id
spring.shardingsphere.sharding.tables.tb_order.key-generator.column=order_id
# 指定tb_order表的主键生成策略为SNOWFLAKE
spring.shardingsphere.sharding.tables.tb_order.key-generator.type=SNOWFLAKE
# 指定雪花算法的worker.id
spring.shardingsphere.sharding.tables.tb_order.key-generator.props.worker.id=100
# 指定雪花算法的max.tolerate.time.difference.milliseconds
spring.shardingsphere.sharding.tables.tb_order.key-generator.props.max.tolerate.time.difference.milliseconds=20

# 指定tb_user表的数据分布情况,配置数据节点,使用Groovy的表达式,逻辑表tb_user对应的节点是:ds2.tb_user_1, ds2.tb_user_2
spring.shardingsphere.sharding.tables.tb_user.actual-data-nodes=ds2.tb_user_$->{1..2}
# 采用行表达式分片策略:InlineShardingStrategy
# 指定tb_user表的分片策略中的分片键
spring.shardingsphere.sharding.tables.tb_user.table-strategy.inline.sharding-column=id
# 指定tb_user表的分片策略中的分片算法表达式,使用Groovy的表达式
spring.shardingsphere.sharding.tables.tb_user.table-strategy.inline.algorithm-expression=tb_user_$->{id%2==0?2:1}
# 指定tb_user表的主键为order_id
spring.shardingsphere.sharding.tables.tb_user.key-generator.column=id
# 指定tb_user表的主键生成策略为SNOWFLAKE
spring.shardingsphere.sharding.tables.tb_user.key-generator.type=SNOWFLAKE
# 指定雪花算法的worker.id
spring.shardingsphere.sharding.tables.tb_order.key-generator.props.worker.id=101
# 指定雪花算法的max.tolerate.time.difference.milliseconds
spring.shardingsphere.sharding.tables.tb_order.key-generator.props.max.tolerate.time.difference.milliseconds=20

# 打开sql输出日志
spring.shardingsphere.props.sql.show=true

4.2、yml配置

application.yml

server:
  port: 8899
  servlet:
    context-path: /sharding-jdbc

spring:
  main:
    # 允许定义相同的bean对象去覆盖原有的
    allow-bean-definition-overriding: true
  shardingsphere:
    props:
      sql:
       # 打开sql输出日志
       show: true
    datasource:
      # 数据源名称,多数据源以逗号分隔
      names: ds1,ds2
      ds1:
        # 数据库连接池类名称
        type: com.alibaba.druid.pool.DruidDataSource
        # 数据库驱动类名
        driver-class-name: com.mysql.cj.jdbc.Driver
        # 数据库url连接
        url: jdbc:mysql://192.168.19.129:3306/sharding_3?serverTimezone=GMT%2B8&characterEncoding=utf8&useUnicode=true&useSSL=false&zeroDateTimeBehavior=CONVERT_TO_NULL&autoReconnect=true&allowMultiQueries=true&failOverReadOnly=false&connectTimeout=6000&maxReconnects=5
        # 数据库用户名
        username: alian
        # 数据库密码
        password: 123456
      ds2:
        # 数据库连接池类名称
        type: com.alibaba.druid.pool.DruidDataSource
        # 数据库驱动类名
        driver-class-name: com.mysql.cj.jdbc.Driver
        # 数据库url连接
        url: jdbc:mysql://192.168.19.130:3306/sharding_4?serverTimezone=GMT%2B8&characterEncoding=utf8&useUnicode=true&useSSL=false&zeroDateTimeBehavior=CONVERT_TO_NULL&autoReconnect=true&allowMultiQueries=true&failOverReadOnly=false&connectTimeout=6000&maxReconnects=5
        # 数据库用户名
        username: alian
        # 数据库密码
        password: 123456
    sharding:
      # 未配置分片规则的表将通过默认数据源定位
      default-data-source-name: ds1
      tables:
        tb_order:
          # 由数据源名 + 表名组成,以小数点分隔。多个表以逗号分隔,支持inline表达式
          actual-data-nodes: ds1.tb_order_$->{1..2}
          # 分表策略
          table-strategy:
            # 行表达式分片策略
            inline:
              # 分片键
              sharding-column: order_id
              # 算法表达式
              algorithm-expression: tb_order_$->{order_id%2==0?2:1}
          # key生成器
          key-generator:
            # 自增列名称,缺省表示不使用自增主键生成器
            column: order_id
            # 自增列值生成器类型,缺省表示使用默认自增列值生成器(SNOWFLAKE/UUID)
            type: SNOWFLAKE
            # SnowflakeShardingKeyGenerator
            props:
              # SNOWFLAKE算法的worker.id
              worker:
                id: 100
              # SNOWFLAKE算法的max.tolerate.time.difference.milliseconds
              max:
                tolerate:
                  time:
                    difference:
                      milliseconds: 20
        tb_user:
          # 由数据源名 + 表名组成,以小数点分隔。多个表以逗号分隔,支持inline表达式
          actual-data-nodes: ds2.tb_user_$->{1..2}
          # 分表策略
          table-strategy:
            # 行表达式分片策略
            inline:
              # 分片键
              sharding-column: id
              # 算法表达式
              algorithm-expression: tb_user_$->{id%2==0?2:1}
          # key生成器
          key-generator:
            # 自增列名称,缺省表示不使用自增主键生成器
            column: id
            # 自增列值生成器类型,缺省表示使用默认自增列值生成器(SNOWFLAKE/UUID)
            type: SNOWFLAKE
            # SnowflakeShardingKeyGenerator
            props:
              # SNOWFLAKE算法的worker.id
              worker:
                id: 101
              # SNOWFLAKE算法的max.tolerate.time.difference.milliseconds
              max:
                tolerate:
                  time:
                    difference:
                      milliseconds: 20
  • 分库策略,这里采用的是行表达式分片策略,对于订单库order_id为奇数就放到ds1.tb_order_1数据源,order_id为偶数就放到ds1.tb_order_2;对于用户库user_id为奇数就放到ds2.tb_user_1数据源,user_id为偶数就放到ds2.tb_user_2,
  • actual-data-nodes :使用Groovy的表达式 ds1.tb_order_$->{1…2},表示逻辑表tb_order对应的物理表是:ds1.tb_order_1ds1.tb_order_2;使用Groovy的表达式 ds2.tb_user_$->{1…2},表示逻辑表tb_user对应的物理表是:ds2.tb_user_1ds2.tb_user_2
  • key-generator :key生成器,需要指定字段和类型,如果是SNOWFLAKE,最好也配置下props中的两个属性: worker.id max.tolerate.time.difference.milliseconds 属性(主要还是yml中配置)
  • table-strategy 表的分片策略,这里只是一个简单的奇数偶数,采用的是 行表达式分片策略 ,需要指定分片键和分片算法表达式(算法支持Groovy的表达式)

五、实现

5.1、实体

Order.java

@Data
@Entity
@Table(name = "tb_order")
public class Order implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "order_id")
    private Long orderId;

    @Column(name = "user_id")
    private Integer userId;

    @Column(name = "price")
    private Integer price;

    @Column(name = "order_status")
    private Integer orderStatus;

    @Column(name = "title")
    private String title;

    @Column(name = "order_time")
    private LocalDateTime orderTime;

}

5.2、持久层

OrderRepository.java

public interface OrderRepository extends PagingAndSortingRepository<Order, Long> {

    /**
     * 根据订单id查询订单
     * @param orderId
     * @return
     */
    Order findOrderByOrderId(Long orderId);
}

UserRepository.java

public interface UserRepository extends PagingAndSortingRepository<User, Long> {

    /**
     * 根据用户id查询订单
     *
     * @param id
     * @return
     */
    User findUserById(Long id);
}

5.3、服务层

OrderService.java

@Slf4j
@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;

    public void saveOrder(Order order) {
        orderRepository.save(order);
    }

    public Order queryOrder(Long orderId) {
        return orderRepository.findOrderByOrderId(orderId);
    }
}

UserService.java

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public void saveUser(User user) {
        userRepository.save(user);
    }

    public User queryUser(Long id) {
        return userRepository.findUserById(id);
    }
}

5.4、测试类

OrderTests.java

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class OrderTests {

    @Autowired
    private OrderService orderService;

    @Test
    public void saveOrder() {
        for (int i = 0; i < 10; i++) {
            Order order = new Order();
            order.setUserId(1000);
            // 随机生成50到100的金额
            int price = (int) Math.round(Math.random() * (10000 - 5000) + 5000);
            order.setPrice(price);
            order.setOrderStatus(2);
            order.setOrderTime(LocalDateTime.now());
            order.setTitle("");
            orderService.saveOrder(order);
        }
    }

    @Test
    public void queryOrder() {
        Long orderId = 845685274628734976L;
        Order order = orderService.queryOrder(orderId);
        log.info("查询的结果:{}", order);
    }

UserTests.java

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserTests {

    @Autowired
    private UserService userService;

    @Test
    public void saveUser() {
        for (int i = 0; i < 8; i++) {
            User user = new User();
            // 随机生成50到100的金额
            int age = (int) Math.round(Math.random() * (35 - 15) + 15);
            user.setUserName("user-" + age);
            user.setAge(age);
            userService.saveUser(user);
        }
    }

    @Test
    public void queryUser() {
        Long orderId = 845687246882754561L;
        User user = userService.queryUser(orderId);
        log.info("查询的结果:{}", user);
    }

}

5.4.1、保存订单数据

运行结果:

15:31:21 465 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 465 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_2 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:20.964, 7687, , 1000, 845685274007977984]
15:31:21 521 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 521 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_1 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:21.519, 5283, , 1000, 845685274528071681]
15:31:21 544 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 545 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_2 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:21.543, 7447, , 1000, 845685274628734976]
15:31:21 568 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 569 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_1 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:21.567, 8478, , 1000, 845685274729398273]
15:31:21 589 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 589 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_2 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:21.588, 9612, , 1000, 845685274813284352]
15:31:21 610 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 611 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_1 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:21.609, 5153, , 1000, 845685274905559041]
15:31:21 637 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 638 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_2 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:21.636, 6311, , 1000, 845685275018805248]
15:31:21 692 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 693 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_1 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:21.691, 8013, , 1000, 845685275249491969]
15:31:21 715 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 716 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_2 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:21.714, 8992, , 1000, 845685275345960960]
15:31:21 737 INFO [main]:Logic SQL: insert into tb_order (order_status, order_time, price, title, user_id) values (?, ?, ?, ?, ?)
15:31:21 737 INFO [main]:Actual SQL: ds1 ::: insert into tb_order_1 (order_status, order_time, price, title, user_id, order_id) values (?, ?, ?, ?, ?, ?) ::: [2, 2023-03-23 15:31:21.736, 5229, , 1000, 845685275438235649]

效果图:
在这里插入图片描述

5.4.2、查询订单数据

  从上面的结果我们可以看到order_id为 845685274628734976 的记录在 sharding_3 库的 tb_order_2 表,实际查询通过 ds1 去查询的请看下面的 Actual SQL

15:33:38 719 INFO [main]:Logic SQL: select order0_.order_id as order_id1_0_, order0_.order_status as order_st2_0_, order0_.order_time as order_ti3_0_, order0_.price as price4_0_, order0_.title as title5_0_, order0_.user_id as user_id6_0_ from tb_order order0_ where order0_.order_id=?
15:33:38 720 INFO [main]:Actual SQL: ds1 ::: select order0_.order_id as order_id1_0_, order0_.order_status as order_st2_0_, order0_.order_time as order_ti3_0_, order0_.price as price4_0_, order0_.title as title5_0_, order0_.user_id as user_id6_0_ from tb_order_2 order0_ where order0_.order_id=? ::: [845685274628734976]
15:33:38 772 INFO [main]:查询的结果:Order(orderId=845685274628734976, userId=1000, price=7447, orderStatus=2, title=, orderTime=2023-03-23T15:31:22)

5.4.3、保存用户数据

运行结果:

15:39:11 492 INFO [main]:Logic SQL: insert into tb_user (age, user_name) values (?, ?)
15:39:11 492 INFO [main]:Actual SQL: ds2 ::: insert into tb_user_2 (age, user_name, id) values (?, ?, ?) ::: [23, user-23, 845687245477662720]
15:39:11 574 INFO [main]:Logic SQL: insert into tb_user (age, user_name) values (?, ?)
15:39:11 574 INFO [main]:Actual SQL: ds2 ::: insert into tb_user_1 (age, user_name, id) values (?, ?, ?) ::: [21, user-21, 845687246077448193]
15:39:11 603 INFO [main]:Logic SQL: insert into tb_user (age, user_name) values (?, ?)
15:39:11 603 INFO [main]:Actual SQL: ds2 ::: insert into tb_user_2 (age, user_name, id) values (?, ?, ?) ::: [16, user-16, 845687246194888704]
15:39:11 630 INFO [main]:Logic SQL: insert into tb_user (age, user_name) values (?, ?)
15:39:11 631 INFO [main]:Actual SQL: ds2 ::: insert into tb_user_1 (age, user_name, id) values (?, ?, ?) ::: [22, user-22, 845687246312329217]
15:39:11 662 INFO [main]:Logic SQL: insert into tb_user (age, user_name) values (?, ?)
15:39:11 662 INFO [main]:Actual SQL: ds2 ::: insert into tb_user_2 (age, user_name, id) values (?, ?, ?) ::: [32, user-32, 845687246446546944]
15:39:11 695 INFO [main]:Logic SQL: insert into tb_user (age, user_name) values (?, ?)
15:39:11 695 INFO [main]:Actual SQL: ds2 ::: insert into tb_user_1 (age, user_name, id) values (?, ?, ?) ::: [20, user-20, 845687246580764673]
15:39:11 731 INFO [main]:Logic SQL: insert into tb_user (age, user_name) values (?, ?)
15:39:11 731 INFO [main]:Actual SQL: ds2 ::: insert into tb_user_2 (age, user_name, id) values (?, ?, ?) ::: [16, user-16, 845687246731759616]
15:39:11 766 INFO [main]:Logic SQL: insert into tb_user (age, user_name) values (?, ?)
15:39:11 766 INFO [main]:Actual SQL: ds2 ::: insert into tb_user_1 (age, user_name, id) values (?, ?, ?) ::: [17, user-17, 845687246882754561]

效果图:
在这里插入图片描述

5.4.4、查询用户数据

运行结果:

15:43:18 497 INFO [main]:Logic SQL: select user0_.id as id1_1_, user0_.age as age2_1_, user0_.create_time as create_t3_1_, user0_.update_time as update_t4_1_, user0_.user_name as user_nam5_1_ from tb_user user0_ where user0_.id=?
15:43:18 498 INFO [main]:Actual SQL: ds2 ::: select user0_.id as id1_1_, user0_.age as age2_1_, user0_.create_time as create_t3_1_, user0_.update_time as update_t4_1_, user0_.user_name as user_nam5_1_ from tb_user_1 user0_ where user0_.id=? ::: [845687246882754561]
15:43:18 577 INFO [main]:查询的结果:User(id=845687246882754561, userName=user-17, age=17, createTime=2023-03-23 07:39:11.0, updateTime=2023-03-23 07:39:11.0)

效果图:

  从上面的结果我们可以看到user_id为 845687246882754561 的记录在 sharding_4 库的 tb_user_1 表,实际查询通过 ds2 去查询的,请看下面的 Actual SQL

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/463207.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Android SeekBar控制视频播放进度(二)——seekTo()不准确

Android SeekBar控制视频播放进度二——seekTo不准确 简介seekTo()视频帧 和 视频关键帧解决办法方法一方法二 简介 上一篇文章中&#xff0c;我们介绍了使用SeekBar控制视频播放&#xff0c;使用过程中发现&#xff0c;对于一些视频&#xff0c;我们拖动SeekBar进度条调节播放…

喜报 | ScanA内容安全云监测获评“新一代信息技术创新产品”

4月20日&#xff0c;在赛迪主办的2023 IT市场年会上&#xff0c;“年度IT市场权威榜单”正式发布。 知道创宇的ScanA内容安全云监测产品荣获“新一代信息技术创新产品”奖项。作为中国IT业界延续时间最长的年度盛会之一&#xff0c;历届IT市场年会公布的IT市场权威榜单已成为市…

备份数据看这里,免费教你苹果手机怎么备份所有数据!

案例&#xff1a;苹果手机怎么算备份成功&#xff1f; 【友友们&#xff0c;手机恢复出厂设置前&#xff0c;怎么样可以备份苹果手机里面的所有数据&#xff1f;】 苹果手机备份数据对于用户来说是非常重要的。在备份数据的同时&#xff0c;还需要学会如何恢复误删的数据。那么…

【微服务笔记22】微服务组件之Sentinel控制台的使用(Sentinel Dashboard)

这篇文章&#xff0c;主要介绍微服务组件之Sentinel控制台的使用&#xff08;Sentinel Dashboard&#xff09;。 目录 一、Sentinel控制台 1.1、下载Dashboard控制台 1.2、搭建测试工程 &#xff08;1&#xff09;引入依赖 &#xff08;2&#xff09;添加配置信息 &#…

微服务生态 -- dubbo -- dubbo3应用级别服务发现(阅读官方文档)

服务发现概述 从 Internet 刚开始兴起&#xff0c;如何动态感知后端服务的地址变化就是一个必须要面对的问题&#xff0c;为此人们定义了 DNS 协议&#xff0c;基于此协议&#xff0c;调用方只需要记住由固定字符串组成的域名&#xff0c;就能轻松完成对后端服务的访问&#x…

236. 二叉树的最近公共祖先【190】

难度等级&#xff1a;中等 上一篇算法&#xff1a; 103. 二叉树的锯齿形层序遍历【191】 力扣此题地址&#xff1a; 236. 二叉树的最近公共祖先 - 力扣&#xff08;Leetcode&#xff09; 1.题目&#xff1a;236. 二叉树的最近公共祖先 给定一个二叉树, 找到该树中两个指定节点…

【MySQL】数据表的增删查改

1、CRUD的解释 C&#xff1a;Create增加 R&#xff1a;Retrieve查询 U&#xff1a;Update更新 D&#xff1a;Deleta删除 2、添加数据 2.1 添加一条记录 添加数据是对表进行添加数据的&#xff0c;表在数据库中&#xff0c;所以还是得先选中数据库&#xff0c;选中数据库还在进行…

STM32F429移植microPython笔记

目录 一、microPython下载。二、安装开发环境。三、编译开发板源码。四、下载验证。 一、microPython下载。 https://micropython.org/download/官网 下载后放在linux中。 解压命令&#xff1a; tar -xvf micropython-1.19.1.tar.xz 二、安装开发环境。 sudo apt-get inst…

MUSIC算法仿真

DOA波达方向估计 DOA&#xff08;Direction Of Arrival&#xff09;波达方向是指通过阵列信号处理来估计来波的方向&#xff0c;这里的信源可能是多个&#xff0c;角度也有多个。DOA技术主要有ARMA谱分析、最大似然法、熵谱分析法和特征分解法&#xff0c;特征分解法主要有MUS…

HTML+CSS+JS 学习笔记(四)———jQuery

&#x1f331;博客主页&#xff1a;大寄一场. &#x1f331;系列专栏&#xff1a;前端 &#x1f331;往期回顾&#xff1a; &#x1f618;博客制作不易欢迎各位&#x1f44d;点赞⭐收藏➕关注​​ 目录 jQuery 基础 jQuery 概述 下载与配置jQuery 2. 配置jQuery jQuery 选…

数据库管理-第七十期 自己?自己(20230425)

数据库管理 2023-04-25 第七十期 自己&#xff1f;自己1 自己吓自己2 自己坑自己3 自己挺自己4 自己懵自己总结 第七十期 自己&#xff1f;自己 来到70了&#xff0c;最近有点卷&#xff0c;写的稍微多了些。 吐槽一下五一调休&#xff0c;周末砍一天&#xff0c;连6天&#x…

重学Java第一篇——数组

本片博客主要讲述了以下内容&#xff1a; 1、 一维数组和二维数组的创建和初始化方式&#xff1b; 2、数组的遍历和赋值 3、java.util.Arrays的常用方法 4、数组在内存中的分布&#xff08;图示&#xff09; 创建数组和初始化 type[] arr_name;//方式一 type arr_name[];//方式…

一家传统制造企业的上云之旅,怎样成为了数字化转型典范?

众所周知&#xff0c;中国是一个制造业大国。在想要上云以及正在上云的企业当中&#xff0c;传统制造企业也占据了相当大的比例。 那么这类企业在实施数字化转型的时候&#xff0c;应该如何着手&#xff1f;我们不妨来看看一家传统制造企业的现身说法。 国茂股份的数字化转型诉…

云原生-如何部署k8s集群与部署sms集群

阿里云开通三台云服务器实例&#xff0c;&#xff08;同一个vpc下&#xff09;&#xff0c;配置安全组入规则&#xff0c;加入80端口 ssh登录三台云服务器 在三台云服务器上部署容器环境&#xff08;安装docker&#xff09;&#xff08;https://www.yuque.com/leifengyang/oncl…

Springboot Mybatis使用pageHelper实现分页查询

以下介绍实战中数据库框架使用的是mybatis&#xff0c;对整合mybatis此处不做介绍。 使用pageHelper实现分页查询其实非常简单&#xff0c;共两步&#xff1a; 一、导入依赖&#xff1b; 二、添加配置&#xff1b; 那么开始&#xff0c; 第一步&#xff1a; pom.xml添加依…

工具链和其他-超级好用的web调试工具whistle

目录 whistle介绍 整体结构 能力 规则 6个使用场景示例 1.修改Host 2.代理 3.替换文件&#xff08;线上报错时&#xff09; 4.替换UA 5.远程调试 6.JS注入 互动 whistle介绍 整体结构 安装&#xff1a; npm install whistle -g cli&#xff1a;whistle help 启动…

前端系列第10集-实战篇

用户体验&#xff1a;性能&#xff0c;交互方式&#xff0c;骨架屏&#xff0c;反馈&#xff0c;需求分析等 组件库&#xff1a;通用表单&#xff0c;表格&#xff0c;弹窗&#xff0c;组件库设计&#xff0c;表单等 项目质量&#xff1a;单元测试&#xff0c;规范&#xff0c;…

mac十大必备软件排行榜 mac垃圾清理软件哪个好

刚拿到全新的mac电脑却不知道该怎么使用&#xff1f;首先应该装什么软件呢&#xff1f;如果你有同样的疑惑&#xff0c;今天这篇文章一定不要错过。接下来小编为大家介绍mac十大必备软件排行榜&#xff0c;以及mac垃圾清理软件哪个好。 一、mac十大必备软件排行榜 1.CleanMyM…

权限提升:AT || SC || PS 提权.(本地权限提升)

权限提升&#xff1a;AT || SC || PS 提权 权限提升简称提权&#xff0c;由于操作系统都是多用户操作系统&#xff0c;用户之间都有权限控制&#xff0c;比如通过 Web 漏洞拿到的是 Web 进程的权限&#xff0c;往往 Web 服务都是以一个权限很低的账号启动的&#xff0c;因此通…

电能计量管理系统在煤矿上的应用

摘要&#xff1a;随着煤矿供电系统管、控一体化的发展需要&#xff0c;本文提出了一种基于矿井光纤网络构成的煤矿电参数计量系统&#xff0c;该系统具有实现变电所各类开关、动力设备的用电高精度计量&#xff1b;远程实时监测各路电参数&#xff1b;远程抄表&#xff1b;远程…