前言
Shardingsphere大量使用了SPI技术,提供良好的可扩展性
参考:https://shardingsphere.apache.org/document/legacy/4.x/document/en/features/spi/
SPI基本概念:https://www.cnblogs.com/jy107600/p/11464985.html
本文以ShardingKeyGenerator接口为例说明SPI在Shardingsphere中的使用
本文的代码都可以在项目源码中找到:https://github.com/apache/shardingsphere/tree/4.1.1
1. ShardingKeyGenerator接口及其子类
org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator
{
Comparable<?> generateKey();
}
ShardingKeyGenerator默认实现了四种生成主键的方式,分别是自增、自减、UUID、SnowFlake方式
org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerator
org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.DecrementKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.UUIDShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator
2. ShardingKeyGenerator SPI的初始化
package org.apache.shardingsphere.spi.algorithm.keygen;
public final class ShardingKeyGeneratorServiceLoader extends TypeBasedSPIServiceLoader<ShardingKeyGenerator> {
// 静态代码块注册ShardingKeyGenerator所有实现类
static {
NewInstanceServiceLoader.register(ShardingKeyGenerator.class);
}
public ShardingKey