流程启动过程
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