Erlang: remote call vs sending messages

北战南征 提交于 2019-12-04 12:14:02

问题


I'd like to execute some procedure on a remote node. And I'm not sure which is the best way to do this. I can write a rpc:call to do this. Or send a message by Remote ! {call, some_procedure} to the node to start the procedure and use receive waiting for the response. So which way is better in erlang? Or they actually are for different usage?


回答1:


It's better to use module rpc, because if you don't: you'll have to manage monitoring of remote node, have to provide unique id of the call, handle timeouts, also you're have to provide wrapper to send-back response with result of function.

But all of these manipulations are generic, and implemented in rpc module.

By the way, there are different variations of remote calls, which implemented in rpc: synchronous and asynchronous calls, cast (send message which doesn't need response), even parallel map function (pmap).

P.S.

Compare - simply using rpc:call vs. implement that from scratch (also, this is simple implementation, which doesn't handle some important cases):

-module(myrpc).
-compile(export_all).

server() ->
        receive
                {{CallerPid, Ref}, {Module, Func, Args}} ->
                        Result = apply(Module, Func, Args),
                        CallerPid ! {Ref, Result}
        end.

call(Node, Module, Func, Args) ->
        monitor_node(Node, true),
        RemotePid = spawn(Node, ?MODULE, server, []),
        Ref = make_ref(),
        RemotePid ! {{self(), Ref}, {Module, Func, Args}},
        receive
                {Ref, Result} ->
                        monitor_node(Node, false),
                        Result;
                {nodedown, Node} ->
                        error
        end.



回答2:


rpc seems to be comprehensive solution, but it has some disadvantages related to scale. rpc uses single 'rex' server to cross node communication and potentially it may be overwhelmed. If you go with rpc, you should monitor this process.

If the communication is the main functionality and it is the top of io/cpu/memory consumer I would consider writing it yourself. On the other hand we may expect improvements from OTP team (and pre-mature optimization is root of all evil!!!).



来源:https://stackoverflow.com/questions/12508539/erlang-remote-call-vs-sending-messages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!