当前位置: 首页 > 工具软件 > hint > 使用案例 >

shardingsphere-jdbc之Mybatis Hint 分片算法

云俊名
2023-12-01

介绍

基于shardingsphere-jdbc 5.1.0 进行单库分表.

规则配置

Hint 分片算法需要用户实现 org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm 接口。 Apache ShardingSphere 在进行路由时,将会从 HintManager 中获取分片值进行路由操作。

try (HintManager hintManager = HintManager.getInstance()) {
      hintManager.addTableShardingValue("t_order", CITIES[1]);

      List<OrderEntity> list = orderRepository.findAll();
      log.info("===>{}", list);
}
  • 使用 hintManager.addDatabaseShardingValue 来添加数据源分片键值。
  • 使用 hintManager.addTableShardingValue 来添加表分片键值。

Hint 行表达式分片算法

类型:HINT_INLINE

属性名称数据类型说明默认值
algorithm-expressionString分片算法的行表达式${value}

1. maven项目依赖

<dependencies>
	<dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
            <version>5.1.0</version>
        </dependency>
	<dependency>
           <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
</dependencies>

2.application.yml配置

spring:
  application:
    name: jdbc-myabtis-hint
  profiles:
    include: jdbc

mybatis:
  mapper-locations: classpath*:/mappers/*-mapper.xml
  type-aliases-package: com.lance.sharding.hint.domain
  configuration:
    default-fetch-size: 20
    default-statement-timeout: 30
    map-underscore-to-camel-case: true
    use-generated-keys: true

logging:
  file:
    name: logs/${spring.application.name}.log
  level:
    org.springframework: info
    com.lance.sharding.hint: debug

3.application-jdbc.yml配置

spring:
  shardingsphere:
    datasource:
      ds:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://127.0.0.1:3306/bbs_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
        password: li123456
        username: root
      names: ds
    rules:
      sharding:
        binding-tables:
          - t_order,t_order_item
        broadcast-tables: t_address
        sharding-algorithms:
          t-order-inline:
            type: HINT_INLINE
            props:
              algorithm-expression: t_order_$->{value}
          t-order-item-inline:
            type: INLINE
            props:
              algorithm-expression: t_order_item_$->{order_id % 2}
        tables:
          t_order:
            actual-data-nodes: ds.t_order_$->{['shanghai','beijing']}
            table-strategy:
              hint:
                sharding-algorithm-name: t-order-inline
          t_order_item:
            actual-data-nodes: ds.t_order_item_$->{0..1}
            table-strategy:
              standard:
                sharding-algorithm-name: t-order-item-inline
                sharding-column: order_id
    props:
      sql-show: true

4.测试Sql脚本

CREATE TABLE `t_order_beijing`
(
    `order_id`    bigint NOT NULL AUTO_INCREMENT,
    `user_id`     int    NOT NULL,
    `address_id`  bigint NOT NULL,
    `city`        varchar(32) NULL DEFAULT NULL,
    `status`      tinyint NULL DEFAULT NULL,
    `creator`     varchar(32) NULL DEFAULT NULL,
    `create_time` datetime NULL DEFAULT NULL,
    `updater`     varchar(32) NULL DEFAULT NULL,
    `update_time` datetime NULL DEFAULT NULL,
    PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic

CREATE TABLE `t_order_shanghai`
(
    `order_id`    bigint NOT NULL AUTO_INCREMENT,
    `user_id`     int    NOT NULL,
    `address_id`  bigint NOT NULL,
    `city`        varchar(32) NULL DEFAULT NULL,
    `status`      tinyint NULL DEFAULT NULL,
    `creator`     varchar(32) NULL DEFAULT NULL,
    `create_time` datetime NULL DEFAULT NULL,
    `updater`     varchar(32) NULL DEFAULT NULL,
    `update_time` datetime NULL DEFAULT NULL,
    PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic

5.单元测试Test

class OrderMapperTests {
  private final static String[] CITIES = {"shanghai", "beijing"};
  @Autowired
  private OrderMapper orderMapper;

  @Test
  @Disabled
  void save() {
    ThreadLocalRandom random = ThreadLocalRandom.current();

    IntStream.range(0, 20).forEach(i -> {
      try (HintManager hintManager = HintManager.getInstance()) {
        hintManager.addTableShardingValue("t_order", CITIES[i % 2]);

        Order order = new Order();
        order.setOrderId(System.nanoTime() + i);
        order.setAddressId(i);
        order.setCity(CITIES[i % 2]);
        order.setUserId(Math.abs(random.nextInt()));
        order.setCreator("user.0" + i);
        order.setUpdater(order.getCreator());
        orderMapper.save(order);
      }
    });
  }

  @Test
  void findAll() {
    try (HintManager hintManager = HintManager.getInstance()) {
      // value[0..1]
      hintManager.addTableShardingValue("t_order", CITIES[1]);
      List<Order> list = orderMapper.findAll();

      log.info("===>{}", list);
    }
  }
}

6.项目完整地址

shardingsphere-jdbc之Mybatis Hint 分片算法 Github 地址

shardingsphere-jdbc之Mybatis Hint 分片算法 Gitee 地址

 类似资料: