Flowable流程启动源码分析

流程启动过程

1.源码执行过程

runtimeService.createProcessInstanceBuilder()
                .processDefinitionKey(instanceTrigger.getProcessDefinitionKey().trim())
                .name(instanceTrigger.getFormName() == null ? "" : instanceTrigger.getFormName().trim())
                .businessKey(instanceTrigger.getFormKey() == null ? "" : instanceTrigger.getFormKey().trim())
                .variables(instanceTrigger.getVariables())
                .tenantId(instanceTrigger.getTenantId())
                .start();

1.1. 启动流程

--> runtimeService.startProcessInstance(this)

1.2. 执行命令

        --> org.flowable.common.engine.impl.cfg.CommandExecutorImpl.execute(new StartProcessInstanceCmd<ProcessInstance>(processInstanceBuilder))
            --> CommandInterceptor first.execute(CommandConfig config, Command<T> command)

1.3. 拦截命令

                //命令拦截器 LogInterceptor -> SpringTransactionInterceptor -> CommandContextInterceptor -> TransactionContextInterceptor -> CommandInvoker
                //org.flowable.common.engine.impl.AbstractEngineConfiguration protected List<CommandInterceptor> customPostCommandInterceptors;
                --> org.flowable.common.engine.impl.interceptor.LogInterceptor.execute(CommandConfig config, Command<T> command)
                    --> org.flowable.common.spring.SpringTransactionInterceptor.execute(final CommandConfig config, final Command<T> command)
                        --> int transactionPropagation = getPropagation(config); //获取事务传播方式:
                        //1.NOT_SUPPORTED 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
                        //2.REQUIRED 支持当前事务,如果当前没有事务,就新建一个事务 (默认)
                        //3.REQUIRES_NEW 新建事务,如果当前存在事务,把当前事务挂起
                            --> org.flowable.common.engine.impl.interceptor.CommandContextInterceptor.execute(CommandConfig config, Command<T> command)
                                --> commandContext = commandContextFactory.createCommandContext(command);
                                --> commandContext.setEngineConfigurations(engineConfigurations);
                                --> org.flowable.common.engine.impl.interceptor.TransactionContextInterceptor.execute(CommandConfig config, Command<T> command)
                                    --> org.flowable.engine.impl.interceptor.BpmnOverrideContextInterceptor.execute(CommandConfig config, Command<T> command)
                                        --> org.flowable.engine.impl.interceptor.CommandInvoker.execute(final CommandConfig config, final Command<T> command)
                                            --> FlowableEngineAgenda agenda = CommandContextUtil.getAgenda(commandContext);

1.4. 计划流程的操作

                                            --> agenda.planOperation(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        commandContext.setResult(command.execute(commandContext));
                                                    }
                                                });
                                            --> executeOperations(commandContext)
                                                --> StartProcessInstanceCmd.execute(CommandContext commandContext)
                                                    --> processInstance = startProcessInstance(processDefinition)
                                                        --> ProcessInstanceHelper.createProcessInstance(ProcessDefinition, )
                                                            --> CommandContextUtil.getHistoryManager(commandContext).recordProcessInstanceStart(processInstance);
                                                                --> HistoricProcessInstanceEntity historicProcessInstance = getHistoricProcessInstanceEntityManager().create(processInstance);
                                                                    --> historicProcessInstanceDataManager.create(processInstanceExecutionEntity);
                                                                --> getHistoricProcessInstanceEntityManager().insert(historicProcessInstance, false);
                                                                    --> AbstractEntityManager.insert(EntityImpl, boolean)

1.5. 插入实体(只提交到缓存)

                                                                    //实体插入(加入缓存)顺序:ProcessInstance->IdentityLinkEntity->HistoricIdentityLinkEntityImpl
                                                                    //->HistoricProcessInstanceEntity->Execution->ActivityInstanceEntity->HistoricActivityInstanceEntity
                                                                        --> getDataManager().insert(entity);
                                                                            --> DbSqlSession.insert(Entity entity)
                                                                                --> insertedObjects.put(clazz, new LinkedHashMap<>()); 
                                                                                --> insertedObjects.get(clazz).put(entity.getId(), entity); //**加入缓存,待事务提交入库
                                                                                --> entityCache.put(entity, false);
                                                            --> eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.HISTORIC_PROCESS_INSTANCE_CREATED, historicProcessInstance)); //HISTORIC_PROCESS_INSTANCE_CREATED
                                                                --> FlowableEventSupport.dispatchEvent(org.flowable.common.engine.api.delegate.event.FlowableEvent)
                                                                --> BpmnModelEventDispatchAction.dispatchEvent(CommandContext commandContext, FlowableEventSupport eventSupport, FlowableEvent event)
                                                            --> eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.PROCESS_CREATED, processInstance)); //PROCESS_CREATED
                                                                --> FlowableEventSupport.dispatchEvent(org.flowable.common.engine.api.delegate.event.FlowableEvent)
                                                                --> BpmnModelEventDispatchAction.dispatchEvent(CommandContext commandContext, FlowableEventSupport eventSupport, FlowableEvent event)
                                                                    --> ((FlowableEventSupport) bpmnModel.getEventSupport()).dispatchEvent(event)
                                                                        --> FlowableEventSupport.dispatchEvent(org.flowable.common.engine.api.delegate.event.FlowableEvent)
                                                            --> eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityWithVariablesEvent(FlowableEngineEventType.ENTITY_INITIALIZED, processInstance, startInstanceBeforeContext.getVariables(), false)); //ENTITY_INITIALIZED
                                                                --> FlowableEventSupport.dispatchEvent(org.flowable.common.engine.api.delegate.event.FlowableEvent)
                                                                --> BpmnModelEventDispatchAction.dispatchEvent(CommandContext commandContext, FlowableEventSupport eventSupport, FlowableEvent event)
                                                                    --> ((FlowableEventSupport) bpmnModel.getEventSupport()).dispatchEvent(event)
                                                                        --> FlowableEventSupport.dispatchEvent(org.flowable.common.engine.api.delegate.event.FlowableEvent)
                                                            --> CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(execution);
                                                                --> org.flowable.engine.impl.persistence.entity.ActivityInstanceEntityManagerImpl.recordActivityStart(ExecutionEntity executionEntity)

1.6. 完成ProcessInstance的创建,并返回

                                                            --> startProcessInstance(processInstance, commandContext, startInstanceBeforeContext.getVariables())
                                                                --> ExecutionEntity execution = processInstance.getExecutions().get(0); // There will always be one child execution created

1.7. 计划流程节点的操作

                                                                --> CommandContextUtil.getAgenda(commandContext).planContinueProcessOperation(execution); //计划第一个流程节点的操作
                                            --> executeOperations(commandContext);

1.8. 循环取出节点,分别执行对应的cmd

                                                //while (!CommandContextUtil.getAgenda(commandContext).isEmpty()) 循环取出流程图所有元素
                                                --> Runnable runnable = CommandContextUtil.getAgenda(commandContext).getNextOperation();
                                                --> executeOperation(runnable);
                                                    --> org.flowable.engine.impl.agenda.ContinueProcessOperation.run()
                                                        --> continueThroughFlowNode(FlowNode flowNode)
                                                            --> executeProcessStartExecutionListeners();
                                                                --> executeExecutionListeners(HasExecutionListeners elementWithExecutionListeners,ExecutionEntity executionEntity, String eventType)
                                                                    --> CommandContextUtil.getProcessEngineConfiguration(commandContext).getListenerNotificationHelper()
                                                                                       .executeExecutionListeners(elementWithExecutionListeners, executionEntity, eventType);
                                                                        --> org.flowable.engine.impl.bpmn.listener.ListenerNotificationHelper.executeExecutionListeners(HasExecutionListeners elementWithExecutionListeners, DelegateExecution execution, String eventType)
                                                                            --> executeSynchronous(flowNode);
                                                                                --> processEngineConfiguration.getEventDispatcher().dispatchEvent(
                                                                                        FlowableEventBuilder.createActivityEvent(FlowableEngineEventType.ACTIVITY_STARTED, flowNode.getId(), flowNode.getName(), execution.getId(),
                                                                                                execution.getProcessInstanceId(), execution.getProcessDefinitionId(), flowNode));
                                                                                    -->org.flowable.engine.impl.bpmn.behavior.FlowNodeActivityBehavior.execute() 
                                                            --> executeActivityBehavior(activityBehavior, flowNode);
                                                            --> executeBoundaryEvents(boundaryEvents, boundaryEventExecutions);
                                                        --> executeSynchronous(flowNode)/executeMultiInstanceSynchronous(flowNode)/executeAsynchronous(flowNode)
                                                            --> CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(execution);
                                                    --> org.flowable.engine.impl.agenda.TakeOutgoingSequenceFlowsOperation.run()
                                                        --> cleanupExecutions(currentFlowElement);
                                                        --> handleActivityEnd(flowNode);
                                                            --> CommandContextUtil.getEventDispatcher(commandContext).dispatchEvent(
                                                                   lowableEventBuilder.createActivityEvent(FlowableEngineEventType.ACTIVITY_COMPLETED, flowNode.getId(), flowNode.getName(),
                                                                         execution.getId(), execution.getProcessInstanceId(), execution.getProcessDefinitionId(), flowNode));
                                                        --> leaveFlowNode(flowNode);
                                                            --> agenda.planContinueProcessOperation(outgoingExecution);
                                            //上面这段会循环执行找出流程图里的所有element: StartEvent id="StartEvent_1" -> sequenceFlow id="Flow_0s4uh4h" -> exclusiveGateway id="Gateway_1x6a8jq" -> sequenceFlow id="Flow_12jwnrf" -> userTask id="Activity_1wajqhb" -> ...

1.9. 按拦截器顺序逆向返回,之后进行事务提交

                            //按拦截器顺序逆向返回,之后进行事务提交
                            --> commandContext.close();
                                --> flushSessions(); 
                                    --> session.flush();
                                        --> flushInserts();
                                            --> flushInsertEntities(entityClass, insertedObjects.get(entityClass).values());
                                                --> flushRegularInsert(entitiesToInsert.iterator().next(), entityClass);

1.10. 提交事务的时候将缓存入库

                                                    --> DbSqlSession.insert(insertStatement, entity); //**执行插入,入库
                                            --> insertedObjects.remove(entityClass); //清空缓存
                                        --> flushUpdates();
                                        --> flushDeletes(); 

2.任务调度过程

ProcessEngineConfigurationImpl.setAsyncExecutorActivate控制着任务调度是否开启

ProcessEngineConfigurationImpl.buildProcessEngine
    --> init();
        --> initAsyncExecutor();
            --> asyncExecutor = defaultAsyncExecutor;
            --> asyncExecutor.setAutoActivate(asyncExecutorActivate); //**asyncExecutorActivate 控制着异步任务调度是否开启
    --> new ProcessEngineImpl(this)
        --> asyncExecutor.start() //if (asyncExecutor != null && asyncExecutor.isAutoActivate())
            --> AbstractAsyncExecutor.start()
                --> initializeRunnables() 
                    --> timerJobRunnable = new AcquireTimerJobsRunnable(this, jobServiceConfiguration.getJobManager());
                    --> resetExpiredJobsRunnable = new ResetExpiredJobsRunnable(resetRunnableName, this, jobEntityManagerToUse);
                    --> asyncJobsDueRunnable = new AcquireAsyncJobsDueRunnable(acquireJobsRunnableName, this, jobEntityManagerToUse)
                --> DefaultAsyncJobExecutor.startAdditionalComponents
                    --> initAsyncJobExecutionThreadPool();
                    --> startJobAcquisitionThread();
                    --> startTimerAcquisitionThread();
                        --> AcquireTimerJobsRunnable.run()
                    --> startResetExpiredJobsThread()
                        --> ResetExpiredJobsRunnable.run()
                            --> resetJobs()
                                --> List<? extends JobInfoEntity> expiredJobs = asyncExecutor.getJobServiceConfiguration().getCommandExecutor()
                                        .execute(new FindExpiredJobsCmd(asyncExecutor.getResetExpiredJobsPageSize(), jobEntityManager));
                                    --> asyncExecutor.getJobServiceConfiguration().getCommandExecutor().execute(
                                            new ResetExpiredJobsCmd(expiredJobIds, jobEntityManager));

3.默认命令拦截器配置

    public Collection<? extends CommandInterceptor> getDefaultCommandInterceptors() {
        if (defaultCommandInterceptors == null) {
            List<CommandInterceptor> interceptors = new ArrayList<>();
            interceptors.add(new LogInterceptor()); //1. LogInterceptor

            if (DATABASE_TYPE_COCKROACHDB.equals(databaseType)) {
                interceptors.add(new CrDbRetryInterceptor());
            }

            CommandInterceptor transactionInterceptor = createTransactionInterceptor(); //2. new SpringTransactionInterceptor(transactionManager);
            if (transactionInterceptor != null) {
                interceptors.add(transactionInterceptor);
            }

            if (commandContextFactory != null) {
                String engineCfgKey = getEngineCfgKey();
                CommandContextInterceptor commandContextInterceptor = new CommandContextInterceptor(commandContextFactory);
                engineConfigurations.put(engineCfgKey, this);
                commandContextInterceptor.setEngineConfigurations(engineConfigurations);
                commandContextInterceptor.setServiceConfigurations(serviceConfigurations);
                commandContextInterceptor.setCurrentEngineConfigurationKey(engineCfgKey);
                interceptors.add(commandContextInterceptor); //3. CommandContextInterceptor
            }

            if (transactionContextFactory != null) {
                interceptors.add(new TransactionContextInterceptor(transactionContextFactory)); //4. TransactionContextInterceptor
            }

            List<CommandInterceptor> additionalCommandInterceptors = getAdditionalDefaultCommandInterceptors(); //5. new BpmnOverrideContextInterceptor()
            if (additionalCommandInterceptors != null) {
                interceptors.addAll(additionalCommandInterceptors);
            }

            defaultCommandInterceptors = interceptors;
        }
        return defaultCommandInterceptors;
    }

3.1自定义拦截器

改造切入点:设置customPostCommandInterceptors

engineConfiguration.setCustomPostCommandInterceptors()

    public void initCommandInterceptors() {
        if (commandInterceptors == null) {
            commandInterceptors = new ArrayList<>();
            if (customPreCommandInterceptors != null) {
                commandInterceptors.addAll(customPreCommandInterceptors);
            }
            commandInterceptors.addAll(getDefaultCommandInterceptors());
            if (customPostCommandInterceptors != null) {
                commandInterceptors.addAll(customPostCommandInterceptors);
            }
            commandInterceptors.add(commandInvoker); //6. CommandInvoker
        }

4.事件监听器

    public void dispatchEvent(FlowableEvent event) {
        if (event == null) {
            throw new FlowableIllegalArgumentException("Event cannot be null.");
        }

        if (event.getType() == null) {
            throw new FlowableIllegalArgumentException("Event type cannot be null.");
        }

        // Call global listeners
        if (!eventListeners.isEmpty()) {
            for (FlowableEventListener listener : eventListeners) {
                dispatchEvent(event, listener);
            }
        }

        // Call typed listeners, if any
        List<FlowableEventListener> typed = typedListeners.get(event.getType());
        if (typed != null && !typed.isEmpty()) {
            for (FlowableEventListener listener : typed) {
                dispatchEvent(event, listener);
            }
        }
    }

改造切入点:
engine.setEventListeners(List eventListeners)
engine.setAdditionalEventDispatchActions(List additionalEventDispatchActions)

    public void initEventDispatcher() {
        if (this.eventDispatcher == null) {
            this.eventDispatcher = new FlowableEventDispatcherImpl();
        }

        if (this.additionalEventDispatchActions == null) {
            this.additionalEventDispatchActions = new ArrayList<>();
            this.additionalEventDispatchActions.add(new BpmnModelEventDispatchAction());
        }

        this.eventDispatcher.setEnabled(enableEventDispatcher);

        if (eventListeners != null) {
            for (FlowableEventListener listenerToAdd : eventListeners) {
                this.eventDispatcher.addEventListener(listenerToAdd);
            }
        }

        if (typedEventListeners != null) {
            for (Entry<String, List<FlowableEventListener>> listenersToAdd : typedEventListeners.entrySet()) {
                // Extract types from the given string
                FlowableEngineEventType[] types = FlowableEngineEventType.getTypesFromString(listenersToAdd.getKey());

                for (FlowableEventListener listenerToAdd : listenersToAdd.getValue()) {
                    this.eventDispatcher.addEventListener(listenerToAdd, types);
                }
            }
        }
    }

最后

  • flowable自带mapper

在这里插入图片描述

Flowable是一个开源的流程引擎,可以用于处理和管理各种类型的业务流程Flowable源码可以在其官方的GitHub仓库上找到,具体地址是https://github.com/flowable/flowable-engine/releases/tag/flowable-6.7.2。 Flowable启动流程有两种方式,但最终都是执行了StartProcessInstanceCmd命令。在我以流程key方式启动分析源码中,启动流程的入口是通过runtimeService.startProcessInstance方法来实现的。 通过研究Flowable源码,可以深入了解其内部的实现机制,从而更好地理解Flowable的工作原理和使用方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [flowable 6.7.2 源码压缩包](https://download.csdn.net/download/weixin_44393822/86790116)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [flowable部署和启动源码解析](https://blog.csdn.net/u012483153/article/details/106736343)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Flowable流程启动源码分析](https://blog.csdn.net/CH_PaulFrank/article/details/116800070)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值