Erlang:远程呼叫与发送消息 [英] Erlang: remote call vs sending messages
问题描述
我想在远程节点上执行一些过程。而且我不知道这是最好的方法。我可以写一个 rpc:call
来做到这一点。或者通过远程发送消息! {call,some_procedure}
到节点启动过程,并使用 receive
等待响应。那么哪个方式在erlang更好?或者他们实际上是用于不同的用途?
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?
推荐答案
最好使用模块 rpc
,因为如果你不这样做:你将不得不管理远程节点的监控,必须提供唯一的呼叫ID,处理超时,还要提供包装器来发送回应
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.
但是所有这些操作都是通用的,并在 rpc
module。
But all of these manipulations are generic, and implemented in rpc
module.
顺便说一下,远程调用有不同的变化,在 rpc
:同步和异步调用,转换(发送不需要响应的消息),甚至并行映射功能( pmap )。
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).
PS
比较 - 只需使用 rpc:call 从头开始实现,这是一个简单的实现,它不处理一些重要的情况):
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.
这篇关于Erlang:远程呼叫与发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!