在运行时在 Camunda 中添加事件处理程序(ExecutionListener 或 TaskListener)

Add event handler (ExecutionListener or TaskListener) at runtime in Camunda

根据 Camunda 的文档 (https://docs.camunda.org/manual/latest/user-guide/process-applications/process-application-event-listeners/),可以将 "global" 事件处理程序(ExecutionListener 或 TaskListener)添加到 ProcessApplication

尽管如此,我还没有找到在运行时添加类似 ("global") 事件处理程序的方法。此功能在 Activiti 中使用引擎的 RuntimeService (https://www.activiti.org/javadocs/org/activiti/engine/RuntimeService.html#addEventListener-org.activiti.engine.delegate.event.ActivitiEventListener-) 的方法 addEventListener 存在,但在 Camunda 的 RuntimeService 中不再存在。

如何在运行时添加 "global" 事件处理程序?
注意:将要添加事件处理程序的 ProcessApplication 无法修改,因为我想从不同的库中添加处理程序。

谢谢大家,

我认为 Activiti 方法 addEventListener 是在 Camunda fork activiti 之后添加的,这就是为什么该方法在 Camunda 的 RuntimeService 上不可用。

如文档所述,您可以定义一个 returns 全局 execution/task 侦听器的流程应用程序。要在运行时定义流程应用程序,您可以使用 EmbeddedProcessApplicationManagementService#registerProcessApplication 方法。

参见以下示例:

EmbeddedProcessApplication processApplication = new EmbeddedProcessApplication() {
  public ExecutionListener getExecutionListener() {
    return new ExecutionListener() {
      public void notify(DelegateExecution execution) throws Exception {
      // do your stuff       
      }              
    };
  }
};

// register app so that it is notified about events
managementService.registerProcessApplication(deploymentId, processApplication.getReference());

社区扩展 camunda-bpm-reactor 允许您注册一个事件总线,它在每次触发侦听器时传播事件。然后,您可以在这些事件上注册侦听器。所以bpmn和listener代码在运行时是耦合的。

@CamundaSelector(type = "userTask", event = TaskListener.EVENTNAME_CREATE)
public class TaskCreateListener implements TaskListener {

   public TaskCreateListener(EventBus eventBus) {
     eventBus.register(this);
   }

   @Override
   public void notify(DelegateTask delegateTask) {
      ...
   }
}