ShardingSphere 集成

返回 Spring Cloud

ShardingSphere-JDBC 以 Jar 嵌入 Spring Boot / Cloud 服务,对 MyBatis / JPA 透明分片;无需改 SQL 中的表名(使用逻辑表)。概念与算法见 ShardingSphere数据库架构


JDBC vs Proxy

模式部署Spring 集成
ShardingSphere-JDBC与应用同进程shardingsphere-jdbc-core + 数据源配置
ShardingSphere-Proxy独立代理应用连 Proxy 如同普通 MySQL

微服务内分片优先 JDBC;多语言统一入口用 Proxy


依赖(5.x)

<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>shardingsphere-jdbc</artifactId>
    <version>5.5.0</version>
</dependency>
<!-- 仍需要具体 JDBC 驱动,如 mysql-connector-j -->

MyBatisJPA 共用同一 DataSource(由 ShardingSphere 包装)。


分片配置示例

spring:
  datasource:
    driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
    url: jdbc:shardingsphere:classpath:sharding.yaml
 
# 或使用 spring.shardingsphere.*(按版本文档为准)

sharding.yaml 示意:

dataSources:
  ds_0:
    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
    jdbcUrl: jdbc:mysql://db0:3306/order_0
    username: root
    password: ***
  ds_1:
    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
    jdbcUrl: jdbc:mysql://db1:3306/order_1
    username: root
    password: ***
 
rules:
  - !SHARDING
    tables:
      t_order:
        actualDataNodes: ds_${0..1}.t_order_${0..15}
        tableStrategy:
          standard:
            shardingColumn: user_id
            shardingAlgorithmName: order-mod
    shardingAlgorithms:
      order-mod:
        type: MOD
        props:
          sharding-count: 16

读写分离(常与分片叠加)

rules:
  - !READWRITE_SPLITTING
    dataSources:
      readwrite_ds:
        writeDataSourceName: master_ds
        readDataSourceNames: [slave_ds_0, slave_ds_1]
        loadBalancerName: round_robin

也可在应用层用 读写分离 + 动态数据源,与 ShardingSphere 二选一或组合(避免重复路由)。


与分布式事务

场景方案
单分片内本地 @Transactional
跨分片 / 跨服务Seata(AT 模式)
推荐默认按分片键设计,避免跨片事务

ShardingSphere 支持 XA / Seata,见 Seata


设计注意

建议
分片键高基数、查询必带(如 user_id
避免跨库 JOIN、全局无序分页
分布式 ID分布式 ID
扩容重分片需数据迁移方案
压测影子库(ShardingSphere 影子规则)

高并发落库:数据层设计


相关链接

Spring

中间件