mulemule4mule-esb

How to send a message to an endpoint in Mule 4 to trigger a flow


With Mule 3 it was possible to send messages asynchronously to an endpoint using MuleClient:

MuleClient client = new MuleClient(muleContext);
client.dispatch("vm://vm.queue", "Message Payload", null);

Is there a way to migrate this functionality in Mule 4 since MuleClient has been removed?

I came across a post that suggested getting the flow by name and publishing the message to the flow as follows

Flow flow = registry.lookupByName("MyFlow").get();
InputEvent event = new DefaultInputEvent();
event.message(Message.of(payload));
flow.execute(event);

but I get a ClassNotFoundException for the class org.mule.runtime.internal.event.DefaultInputEvent


Solution

  • Using Harshank's recommendation I was able to push messages to a flow simply by getting a reference to the flow and triggering the flow by sending messages to the source.

    Flow flow = registry.lookupByName(flowName).get();
    ComponentLocation location = DefaultComponentLocation.from(flowName + "/source");
    ...
    Message message = Message.of(payload);
    CoreEvent coreEvent = CoreEvent.builder(EventContextFactory.create(flow, location)).message(message).build();
    flow.process(coreEvent);
    

    This is a much cleaner solution than what is implemented in the blog and works from beans initialized in the Spring module. As aled mentioned, this is bad practice, but in the interest of time it is a solution.