BPMN 2.0 defines events and tasks catching messages. The following is a fragment of a process waiting for an order to be cancelled:
In BPMN 2.0 XML you have to provide a name for the message you want to catch:
<bpmn2:definitions ...>
...
<bpmn2:message id="<b>Message_1</b>" name="<b>orderCancelled</b>"/>
...
<bpmn2:process id="Process_1" isExecutable="false">
...
<bpmn2:intermediateCatchEvent id="IntermediateCatchEvent_2" name="Order
Cancelled">
<bpmn2:messageEventDefinition messageRef="<b>Message_1</b>"/>
</bpmn2:intermediateCatchEvent>
</bpmn2:process>
New Fluent API
Camunda Engine now features a fluent DSL for correlating this message to the process engine:
runtimeService.createMessageCorrelation("<b>orderCancelled</b>")
.processInstanceBusinessKey("someOrderId")
.setVariable("CANCEL_REASON", "someReason")
.setVariable("CANCEL_TIMESTAMP", new Date())
.correlate();
The fluent DSL makes it easy to define a complex correlation set based on different restrictions. The above example correlates the message on the business key. On top of that, correlation based on process variables and process instance id is supported:
runtimeService.createMessageCorrelation("<b>orderCancelled</b>")
.processInstanceVariableEquals("orderId", "someOrderId")
.processInstanceVariableEquals("customerId", "someCustomerId")
.correlate();
runtimeService.createMessageCorrelation("<b>orderCancelled</b>")
.processInstanceId("someProcessInstanceId")
.correlate();
The API also makes it easy to provide the message payload as a single or multiple variables through setVariable(varName, value).
More Efficient than Query + Trigger
We recommend using the fluent DSL or the RuntimeService.correlateMessage(…) methods introduced in 7.0 over the Query + Trigger pattern. Using the Query + Trigger pattern you first query for an execution having a message event subscription and then trigger that execution:
Not as efficient:
// Query
Execution e = runtimeService.createExecutionQuery()
.processInstanceBusinessKey("someOrderId")
.messageEventSubscriptionName("<b>orderCancelled</b>")
.singleResult();
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("CANCEL_REASON", "someReason");
variables.put("CANCEL_TIMESTAMP", new Date());
// Trigger
runtimeService.messageEventReceived("<b>orderCancelled"</b>, e.getId(), variables);
The Query + Trigger pattern has two disadvantages:
- More lines of code 🙂
- Two process engine commands instead of a single one. This makes it less efficient in terms of performance.