基于 SpringBoot2.4.1 快速搭建一个 Demo,主要 jar 包依赖版本分别是:
- org.apache.shardingsphere.sharding-jdbc-spring-boot-starter:4.1.1
- org.mybatis.spring.boot.mybatis-spring-boot-starter:2.1.4
在最新的ShardingSphere发行版中,提供了大量的SPI扩展点,开发可以利用SPI扩展点满足各式各样的业务场景。但在官方文档里并未找到对扩展点的详细介绍,因此只能通过阅读源码的方式,寻找ShardingSphere提供的扩展点。
首先通过源码目录结构上,我们看到一个shardingsphere-spi模块
通过该模块下的 NewInstanceServiceLoader
类引用,我们可以查看到Shardingsphere里提供的全部扩展点,下面对扩展点进行一个简单的分类梳理。
扩展点分类
钩子类
- org.apache.shardingsphere.underlying.common.hook.RootInvokeHook
- org.apache.shardingsphere.sql.parser.hook.ParsingHook
- org.apache.shardingsphere.underlying.route.hook.RoutingHook
- org.apache.shardingsphere.underlying.executor.hook.SQLExecutionHook
装饰器
- org.apache.shardingsphere.underlying.route.decorator.RouteDecorator
- org.apache.shardingsphere.underlying.rewrite.context.SQLRewriteContextDecorator
- org.apache.shardingsphere.underlying.merge.engine.decorator.ResultDecoratorEngine
- org.apache.shardingsphere.underlying.merge.engine.merger.ResultMergerEngine
加密器
- org.apache.shardingsphere.encrypt.strategy.spi.Encryptor
自定义分布式唯一ID
- org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator
主从轮训算法
- org.apache.shardingsphere.spi.masterslave.MasterSlaveLoadBalanceAlgorithm
自定义时间生成策略
- org.apache.shardingsphere.sharding.route.spi.TimeService
数据源属性配置
- org.apache.shardingsphere.spring.boot.datasource.DataSourcePropertiesSetter
SQL解析器
- org.apache.shardingsphere.sql.parser.spi.SQLParserConfiguration
对于以上SPI扩展点,如果需要知道在何时使用,那么还需要了解扩展点在整个SQL执行过程中调用顺序。
SPI扩展点时序图
下面是基于ShardingDataSource数据源的一个查询语句时序图,因此有些SPI扩展点未涉及到,如:Encryptor(加密数据源才用到)
说明
- 在执行一个SQL语句时,首先会去获取一个连接
ShardingConnection
,这时候在构造器中会执行RootInvokeHook
的start
方法; - 接着在执行SQL的时候会注册路由装饰器
RouteDecorator
; - 然后开始进行路由,在路由的时候需要先去解析SQL,此时会执行
ParsingHook
扩展点里方法; - 获取到解析好的SQL语句后,开始执行路由装饰器
RouteDecorator
中的decorate方法,获取路由结果(具体执行的库和表); - 获取真正要执行的库表后,注册重写装饰器
SQLRewriteContextDecorator
,接着执行装饰器中的decorate
方法获取重写后可执行的实际SQL语句; - 接下来开始执行SQL语句,在真正执行的前后会执行
SQLExecutionHook
中的方法; - 获取SQL执行结果后,如果需要进行结果合并,会执行注册后的
ResultDecoratorEngine
,并调用decorate
方法对结果进行合并装饰; - 返回结果后,会关闭(回收)连接,此时执行
RootInvokeHook
中的finish
方法。
除了上面时序图中提到的SPI扩展点之前,像Encryptor
与ResultDecoratorEngine
是在加密数据源的情况下才会用到。主从算法、时间生成算法以及分布式唯一ID生成策略比较简单,数据源属性配置只会在服务启动的时候拉去一次。SQL解析器允许我们自定义SQL解析规则,但一般情况下我们都使用ShardingSphere自带的SQL解析器,安全可靠。
那利用上面的SPI扩展点,我们可以实现哪些功能?如何根据业务需求合理使用上面的扩展点呢?接下来的文章我们将挑选一些常用的扩展点进行分析介绍。