-
Notifications
You must be signed in to change notification settings - Fork 18
Dispatchers
Sometimes you want route decision making to be done by the sender, and not the receiver. That's where dispatchers come in. Here's an example:
var pid1 = spawn("proc1", ... );
var pid2 = spawn("proc2", ... );
var pid3 = spawn("proc3", ... );
ProcessId pid = Dispatch.broadcast(pid1, pid2, pid3);
tell(pid, msg);In that example 3 processes are grouped into one ProcessId. You can then tell, ask, subscribe, etc. because it's just a regular ProcessId. The Process system itself can spot that there are multiple processes referenced and it deals with it at the time of dispatch, without a router or proxy Process. So 3 messages will be sent to 3 processes, and its the sender that is doing it.
In the above example pid looks like this:
/disp/broadcast/[/node-name/user/proc1,/node-name/user/proc2,/node-name/user/proc3]The disp part tells the system to use a named dispatcher, the broadcast part is the name of the dispatcher (you can register your own dispatchers via Dispatch.register(...)). There are several built in dispatchers:
Dispatch.broadcast(...)Dispatch.random(...)Dispatch.roundRobin(...)Dispatch.random(...)Dispatch.first(...)Dispatch.second(...)Dispatch.third(...)Dispatch.last(...)
The name of the dispatcher decides the bespoke behaviour to run on the rest of the ProcessId: [/node-name/user/pid1,/node-name/user/pid2,/node-name/user/pid3]
You can also register dispatchers as registered processes. This can give router like behaviour even though the dispatcher is doing the routing work.
ProcessId pid = Dispatch.random(pid1, pid2, pid3);
Process.register("load-balance", pid);
// Will send a "Hello" to a random Process in the dispatcher list
tell("@load-balance", "Hello"); The name "@load-balance" can be used from anywhere in the cluster, it only needs to be registered once. So as you can see, dispatchers combined with registered processes are a very powerful feature for routing messages without the need for gatekeeper routers.