当使用ShardingSphere时,如何自定义分片算法并集成到Hibernate?
解读
国内金融、运营商、政务云等核心系统跑在 JBoss EAP 上的比例极高,这些系统往往单表过 10 亿行,必须做水平分库分表。ShardingSphere-JDBC 因“无代理、直接 jar 依赖”被大量采用,而 Hibernate 又是 JBoss EAP 默认的 JPA Provider。面试官问“自定义分片算法并集成到 Hibernate”,并不是让你背 SPI 名称,而是考察四点:
- 是否理解 JBoss EAP 模块化类加载与 ShardingSphere 的 TCCL 冲突;
- 能否把算法做成红帽认可的“模块”,支持热插拔与 10 年长生命周期;
- 是否掌握 Hibernate 5.3/6.x 在 EAP 7.4/8.0 中的字节码增强与二级缓存交互;
- 能否给出可灰度、可回滚、可观测的完整落地路径。
一句话:既要让算法跑在 WildFly 内核里,又不能让 Hibernate 感知到“自己被打补丁”。
知识点
- JBoss Modules 隔离机制:module.xml、slot、依赖导出、filter 与 TCCL 的关系。
- ShardingSphere 5.x 内核:
- 分片 SPI 接口:StandardShardingAlgorithm、ComplexKeysShardingAlgorithm、HintShardingAlgorithm;
- 配置入口:ShardingRuleConfiguration、AlgorithmConfiguration;
- 生命周期:ShardingSphereDataSource 创建时通过 SPI 加载算法,之后不再刷新。
- Hibernate 集成点:
- EAP 7.4 内置 Hibernate ORM 5.3,通过 JPA 2.2 启动;
- 物理数据源由 ShardingSphereDataSource 封装,Hibernate 只看到一个“逻辑库”;
- 二级缓存(Infinispan)键值里包含真实表名,需重写 CacheKeyImplementation 的 toString() 避免缓存穿透。
- 国内合规:
- 国密 SM4 字段级加密后分片,需要算法里调用 JCE 提供者,必须通过 JBoss EAP 的 security-domain 授权;
- 等保 2.0 要求审计,算法类需打 @Audit 注解接入 Red Hat JBoss EAP Logging 子系统。
- 灰度与观测:
- 利用 EAP 的 “deployment-overlay” 给不同机房下发不同 algorithm-class;
- 通过 MicroProfile Metrics 暴露分片命中率,接入 Prometheus + Grafana。
答案
步骤一:创建 JBoss Module
在 $EAP_HOME/modules/system/layers/shard/com/alipay/shardingsphere/main 下放置
- module.xml
- custom-shard-algorithm-1.0.0.jar
module.xml 关键片段:
<module name="com.alipay.shardingsphere" slot="main">
<resources>
<resource-root path="custom-shard-algorithm-1.0.0.jar"/>
</resources>
<dependencies>
<module name="org.apache.shardingsphere.shardingsphere-jdbc-core" slot="main" export="true"/>
<module name="javax.api"/>
</dependencies>
</module>
步骤二:实现算法
public final class BankAcctShardingAlgorithm implements StandardShardingAlgorithm<Long> {
@Override
public String doSharding(Collection<String> dsNames,
PreciseShardingValue<Long> value) {
long acctId = value.getValue();
// 国内银行常用 17 位账号,取 4 位地区码
String region = String.valueOf(acctId).substring(8, 12);
return dsNames.stream()
.filter(ds -> ds.endsWith("_" + region))
.findFirst()
.orElseThrow(() -> new IllegalStateException("region not found"));
}
@Override
public Properties getProps() { return new Properties(); }
@Override
public void init(Properties props) { }
}
META-INF/services 下新建
org.apache.shardingsphere.sharding.spi.ShardingAlgorithm
内容:
com.alipay.shardingsphere.BankAcctShardingAlgorithm
步骤三:在 EAP 中封装 ShardingSphereDataSource
@Singleton
@Startup
public class ShardingDataSourceProducer {
@Produces
@ApplicationScoped
@Named("shardingDS")
public DataSource create() {
ModeConfiguration mode = new ModeConfiguration("Standalone", null);
Map<String, DataSource> real = createRealDataSources(); // 真实 druid/hikari 池
ShardingRuleConfiguration rule = new ShardingRuleConfiguration();
rule.getTables().add(getAcctTableRule());
rule.getShardingAlgorithms().put("acct-alg",
new AlgorithmConfiguration("CLASS_BASED",
PropertiesBuilder.build("strategy", "standard",
"algorithmClassName",
"com.alipay.shardingsphere.BankAcctShardingAlgorithm")));
return ShardingSphereDataSourceFactory.createDataSource("logic_db", mode, real, rule, new Properties());
}
}
步骤四:让 Hibernate 使用逻辑数据源
在 persistence.xml 中删除所有 <jta-data-source> 与 <non-jta-data-source>,改用
<persistence-unit name="primary" transaction-type="JTA">
<jta-data-source>java:jboss/datasources/ShardingSphereDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>
<!-- 禁用 hibernate 自动建表,由 ShardingSphere 管理 -->
<property name="hibernate.hbm2ddl.auto" value="none"/>
<!-- 二级缓存键重写 -->
<property name="hibernate.cache.region.factory_class"
value="org.jboss.as.jpa.hibernate5.infinispan.InfinispanRegionFactory"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
</properties>
</persistence-unit>
在 standalone-full-ha.xml 里新增
<datasource jndi-name="java:jboss/datasources/ShardingSphereDS"
pool-name="ShardingSphereDS" enabled="true" use-java-context="true">
<connection-url>jdbc:shardingsphere:logic_db</connection-url>
<driver>shardingsphere</driver>
</datasource>
<drivers>
<driver name="shardingsphere" module="org.apache.shardingsphere">
<driver-class>org.apache.shardingsphere.driver.ShardingSphereDriver</driver-class>
</driver>
</drivers>
步骤五:热更新与灰度
- 使用 :reload --use-deployment-overlay=true 推送新 algorithm jar;
- 通过 custom metric 暴露分片命中率:
@Metric(name = "shard_hit_rate", absolute = true, unit = MetricUnits.PERCENT)
private AtomicLong hit = new AtomicLong();
- 若需回滚,直接 overlay 移除并 reload,无需重启 EAP 实例。
拓展思考
- 如果 EAP 以域模式运行,算法 jar 需要放到 domain/content 仓库,并通过 CLI 下发到各 server-group;此时要注意 Profile 中模块依赖版本一致性,否则会出现 ClassNotFoundException。
- 当 ShardingSphere 升级为 5.4 的 DistSQL 模式后,算法可以在线 CREATE SHARDING ALGORITHM,但 EAP 的模块隔离仍要求你把算法类提前装载到 modules 层,否则 DistSQL 会报 “algorithm class not found in classpath”。
- 若项目同时引入 Hibernate Reactive(EAP 8 支持),算法里不能再依赖 JDBC 接口,需要重写为 ReactiveShardingAlgorithm,并适配 Vert.x 的 EventLoop 线程模型,避免阻塞。
- 国内信创环境使用鲲鹏 + OpenJDK 毕昇,算法里若含 JNI 加速(如雪花算法),需重新编译 so 并打包到 modules/native 目录,再通过 <native> 标签显式依赖。