sharding-core-execute

  • 模块结构
    sharding-core-execute的主要功能是将路由和改写生成的RoutingUnit对象(RoutingUnit内部含有SQLUnit),产生执行QueryResult。按功能分类可以分成四个部分:
  1. org.apache.shardingsphere.core.execute.hook。在执行的关键操作过程中,发送事件,用于跟踪和事务。
  2. org.apache.shardingsphere.core.execute.metadata。主要提供了加载获取TableMetaData的功能,主要存储表的元数据信息,如表中的列名,数据类,列是否为主键。
  3. org.apache.shardingsphere.core.execute.sql。主要有两个子包:prepare和execute。prepare的作用是在执行前搜集信息,产生ShardingExecuteGroup的集合。
    execute的作用是将ShardingExecuteGroup中StatementExecuteUnit发送到数据库进行执行。
  4. org.apache.shardingsphere.core.execute。 包含ShardingExecuteEngine、SharidngExecuteCallback等重要类,是整个执行模块的核心部分。
  • 模块结构图
  • 主要逻辑流程和关键类分析
    分片执行的主要逻辑是从sharding-jdbc-core的StatementExecutor开始的,真正执行的部分位于sharding-core-execute中,以查询为例,主要逻辑流程图如下。其中,虚线箭头表示从属关系,实线表示执行顺序。
  • 设计模式和设计原则
  1. 模板方法
    SQLExecuteCallback类的execute(final Collection statementExecuteUnits, final boolean isTrunkThread, final Map shardingExecuteDataMap)方法使用了模板方法模式,父类SQLExecuteCallback定义了整个算法的骨架,让子类去实现具体的细节。executeSQL(RouteUnit routeUnit, Statement statement, ConnectionMode connectionMode)就是留给子类自定义的细节部分,使得子类在不变更整体算法的情况下,就可以重新定义该算法的特定步骤。
  2. 依赖倒转原则
    SQLExecutePrepareCallback是一个接口类。BatchPreparedStatementExecutor和PreparedStatementExecutor对与这个类有依赖,由于这个类是个接口,所以调用者可以,在使用前根据实际情况,再定义接口中的抽象方法。这种使用方式对于调用者更加灵活,可以依据场景和需求,自定义相关抽象方法。
  • Java编程技巧
  1. com.google.common.collect.Lists
    SQLExecutePrepareTemplate.getSQLExecuteGroups()方法中使用了Lists,Lists.partition(sqlUnits, desiredPartitionSize);,可以将原本的List切分成多个List。
  2. com.google.common.util.concurrent
    ShardingExecutorService.ShardingExecutorService(final int executorSize, final String nameFormat)方法中,使用了异步回调线程池。同时,设定了JVM关闭时线程池采用的动作。
    在多线程编程中异步回调使得原本需要阻塞等待的异步结果,因为回调的存在而不用等待。
    1
    2
    3
    executorService = MoreExecutors.listeningDecorator(getExecutorService(executorSize, nameFormat));
    MoreExecutors.addDelayedShutdownHook(executorService, 60, TimeUnit.SECONDS);