ShardingSphereConfig 配置分表与不分表

一、需求背景与方案选型

在实际业务场景中,我们经常会遇到这样的需求:某些核心业务表需要按月分表存储历史数据,同时存在大量不需要分表的常规业务表。本文将基于 Spring Boot + MyBatis-Plus + ShardingSphere 技术栈,演示如何实现混合数据源的分表与单表共存配置。

二、环境准备

1. 核心依赖版本

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.7</version>
</dependency>
<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>shardingsphere-jdbc</artifactId>
    <version>5.5.1</version>
</dependency>

2. 基础配置(application.yml)

spring:
  application:
    name: application
  main:
    #允许在容器中覆盖已存在的 Bean
    allow-bean-definition-overriding: true
  shardingsphere:
    url: jdbc:mysql://127.0.0.1:3306/test
    username: root
    password: 123456

三、分表配置实现


/**
 * 分表配置类
 */
@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "spring.shardingsphere")
public class ShardingSphereConfig {

    @NotNull
    private String driverClassName;
    @NotNull
    private String url;
    @NotNull
    private String username;
    @NotNull
    private String password;

    DruidDataSource getDruidDataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
       
        return druidDataSource;
    }



    @Bean
    public DataSource createShardingSphereDataSource() throws Exception {
        // 配置数据源
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put("test", getDruidDataSource());

        // 创建 ShardingRuleConfiguration
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();


        // 配置 tablename 表规则
        ShardingTableRuleConfiguration tableRuleConfig = new ShardingTableRuleConfiguration("tablename", "test" + ".tablename$->{2020}${0}${1..9}," + "test" + ".tablename_$->{2020}${10..12}");
        tableRuleConfig .setTableShardingStrategy(new StandardShardingStrategyConfiguration("date", "date_inline"));
        shardingRuleConfig.getTables().add(tableRuleConfig );

       // 配置 tablename 表的分片算法
        Properties intervalProps = new Properties();
        intervalProps.setProperty("datetime-pattern", "yyyyMM");
        intervalProps.setProperty("datetime-lower", "202001");
        intervalProps.setProperty("datetime-upper", "202012");
        intervalProps.setProperty("sharding-suffix-pattern", "yyyyMM");
        intervalProps.setProperty("datetime-interval-amount", "1");
        intervalProps.setProperty("datetime-interval-unit", "MONTHS");
        shardingRuleConfig.getShardingAlgorithms().put("date_inline", new AlgorithmConfiguration("INTERVAL", intervalPropsBill));


        return ShardingSphereDataSourceFactory.createDataSource("test", dataSourceMap, ruleConfigs, props);
    }

}

如果库中单表和分表混合,那就需要加上单表的配置


        // 创建 SingleRuleConfiguration(单表规则)
        SingleRuleConfiguration singleRuleConfig = new SingleRuleConfiguration();
        singleRuleConfig.setTables(Collections.singletonList("*.*")); // 加载所有单表

        // 将单表规则加入规则集合
        ruleConfigs.add(singleRuleConfig);     // 单表规则

以上便是配置分表的配置

🌟 致创新者的寄语

技术合规不是创意的枷锁,而是商业化的基石。愿每个技术理想都能找到合规落地的航道,与平台规则共舞,在数字世界绽放独特光芒。

💬 互动话题

你在开发过程中遇到过哪些"意想不到"的问题?欢迎留言交流经验!

### 实现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]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值