springboot+shardingsphere+mybatis-plus

工作中经常遇到大数据量的问题,每天的数据量可达百万,需要进行分库分表,从网上找了很多博客学习,经常遇到各种各样的问题,大都是版本选择和配置文件错误,其实仔细研究官方文档就可以了,今天总算是跑起来了,测试也没什么大问题,后面继续优化。

一、框架版本

1、shardingsphere5.5.0

2、springboot3.2.11

3、mybatis-plus3.5.5

二、maven依赖

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

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

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

        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>shardingsphere-jdbc</artifactId>
            <version>5.5.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.shardingsphere</groupId>
                    <artifactId>shardingsphere-test-util</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

三、配置文件(application.yml)

spring:
  main:
    allow-bean-definition-overriding: true
  application:
    name: ls-backend
  datasource:
    driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
    url: jdbc:shardingsphere:classpath:sharding1.yaml
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB
server:
  port: 8085
  servlet:
    context-path: /
    encoding:
      force-response: true


#Mybatis扫描
mybatis:
  config-location: classpath:/mybatis-config.xml

mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

四、sharding配置文件(sharding.yaml)

dataSources:
  ds0:
    driverClassName: com.mysql.cj.jdbc.Driver
    dataSourceClassName: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/ds0?useUnicode=true&useSSL=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8
    username: root
    password: root
  ds1:
    driverClassName: com.mysql.cj.jdbc.Driver
    dataSourceClassName: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/ds1?useUnicode=true&useSSL=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8
    username: root
    password: root
rules:
- !SHARDING
  tables:
    flight:
      actualDataNodes: ds0.flight_$->{0..1}
      tableStrategy:
        standard:
          shardingColumn: id
          shardingAlgorithmName: flight-id-inline
  shardingAlgorithms:
    flight-id-inline:
      type: INLINE
      props:
        algorithm-expression: flight_$->{id % 2}
props:
  sql-show: true

这块要特别注意,属性名要严格遵守驼峰,"- !SHARDING"必须要加,目前不明白为什么,这块是完全按照官方文档来的,还有就是官方文档中写的url是jdbcUrl,但是运行会报错,dubug发现这块取url时使用的是url,故将此处改为url可正常运行。

五、测试

使用mybatis-plus新增数据,根据日志可发现shardingsphere会根据分片算法将逻辑表名变更为实际表名。日志如下:

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@165b679a] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@412916513 wrapping org.apache.shardingsphere.driver.jdbc.core.connection.ShardingSphereConnection@5ece1773] will not be managed by Spring
==>  Preparing: SELECT id,num,date FROM flight WHERE id=?
==> Parameters: 2(Integer)
2024-11-06T10:55:42.313+08:00  INFO 9892 --- [ls-backend] [nio-8085-exec-4] ShardingSphere-SQL                       : Logic SQL: SELECT id,num,date FROM flight WHERE id=?
2024-11-06T10:55:42.313+08:00  INFO 9892 --- [ls-backend] [nio-8085-exec-4] ShardingSphere-SQL                       : Actual SQL: ds0 ::: SELECT id,num,date FROM flight_0 WHERE id=? ::: [2]
<==    Columns: id, num, date
<==        Row: 2, 2, 2024-11-06 10:35:02
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@165b679a]

flight逻辑表名会根据取模算法替换为实际表名。

结语

遇到问题不要慌,静下心来看看文档,多看看框架源代码。

这是第一次接触shardingsphere,有很多详细问题没有理解透彻,大佬勿喷!!!

### 实现ShardingSphere 5.5.0按天分表功能 #### 配置概述 在 ShardingSphere 中实现按天分表的核心在于定义合适的分片策略,通过自定义分片键及其对应的分片算法来完成逻辑表向实际物理表的映射[^1]。 --- #### 数据库设计 假设有一个名为 `order` 的逻辑表,每天会生成一个新的物理表,例如: - `order_20231001` - `order_20231002` 这些物理表可以通过日期字段(如 `create_date` 或 `order_time`)进行区分。每张表的设计应保持一致,以便统一管理[^4]。 --- #### Maven依赖配置 为了集成 ShardingSphere 5.5.0 到 Spring Boot 项目中,需添加如下依赖: ```xml <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId> <version>5.5.0</version> </dependency> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.33</version> </dependency> ``` 以上依赖提供了核心功能以及 YAML 文件解析能力[^4]。 --- #### 配置文件 (application.yml) 以下是基于 Spring Boot 的配置示例,用于设置按天分表的相关参数: ```yaml spring: shardingsphere: datasource: names: ds ds: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://localhost:3306/demo?serverTimezone=UTC&useSSL=false username: root password: root rules: sharding: tables: order: actual-data-nodes: ds.order_$->{2023..2099}[$->{1..12}][$->{1..31}] table-strategy: standard: sharding-column: create_date precise-algorithm-class-name: com.example.demo.algorithm.DateShardingAlgorithm key-generate-strategy: column: order_id key-generator-class-name: org.apache.shardingsphere.core.keygen.DefaultKeyGenerator props: sql-show: true ``` 在此配置中: - **actual-data-nodes**: 定义了物理表的实际命名规则,采用占位符 `$->{}` 动态生成年份、月份和日历[^1]。 - **table-strategy**: 使用标准分片策略,指定分片列 (`create_date`) 及其精确匹配算法类名[^4]。 --- #### 自定义分片算法 创建一个 Java 类作为分片算法实现,具体代码如下: ```java package com.example.demo.algorithm; import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm; import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; public class DateShardingAlgorithm implements PreciseShardingAlgorithm<Date> { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); @Override public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) { String dateStr = DATE_FORMAT.format(shardingValue.getValue()); return "order_" + dateStr; } } ``` 此算法接收分片值并返回目标表名称,依据传入的时间戳格式化为 `yyyyMMdd` 形式的字符串。 --- #### 测试案例 ##### 插入操作 当插入一条订单记录时,系统会自动根据 `create_date` 字段分配至对应的目标表中。 ```java Order order = new Order(); order.setOrderId(1L); order.setCreateDate(new Date()); // 当前时间 orderRepository.save(order); ``` 如果当前时间为 `2023-10-08`,则该条记录会被存储到 `order_20231008` 表中。 ##### 查询操作 对于范围查询或条件过滤,可以利用 ShardingSphere 提供的路由机制优化 SQL 执行效率。 ```sql SELECT * FROM order WHERE create_date >= '2023-10-01' AND create_date <= '2023-10-07'; ``` 上述语句仅会在符合条件的几张表上运行,而非全量扫描所有历史数据[^4]。 --- #### 注意事项 1. 物理表的数量增长较快,建议定期清理过期数据以节省存储空间。 2. 如果涉及跨表联合查询,则可能需要额外配置广播表或其他解决方案[^3]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值