如何获取erlang集群中当前节点名称?
我的模块中有一个名为“message/2”的函数,名为“message_passing”,该函数在另一个函数 hash/1 中调用。我需要 3 个名为 node1、node2 和 node3 的节点,但是当我想在名为“Current_Node”的变量中获取当前节点时,它不起作用。它显示一个错误。它无法获取我的变量中的当前节点。
** exception error: no true branch found when evaluating an if expression
in function message_passing:hash/1
hash(H)->
Current_Node=node(),
if
Current_Node==node1->
message(node2,H),
message(node3,H);
Current_Node==node2->
message(node1,H),
message(node3,H);
Current_Node==node3->
message(node1,H),
message(node2,H)
end
I have a function named "message/2" in my module named "message_passing",This function is called in another function hash/1. I need 3 nodes named node1, node2, and node3, but when I want to get the current node in a variable named "Current_Node" it doesn't work. It shows an error. It is unable to get the current node in my variable.
** exception error: no true branch found when evaluating an if expression
in function message_passing:hash/1
hash(H)->
Current_Node=node(),
if
Current_Node==node1->
message(node2,H),
message(node3,H);
Current_Node==node2->
message(node1,H),
message(node3,H);
Current_Node==node3->
message(node1,H),
message(node2,H)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不确定您是否只是在代码中使用示例,但 bif node() 不会返回仅包含节点名称的原子,还会返回主机名。
这就是为什么你的代码不能像你想象的那样工作的原因。
Not sure if you are just using examples in your code, but the bif node() does not return an atom with just the node name, the host name is also returned.
which would be the reason why your code is not working as you think it should.
有一些内置函数可以在这里提供帮助,
erlang:node/0
返回它所评估的节点的名称,erlang:nodes(connected)
返回您当前连接到的节点的名称。因此,您可以编写
hash/1
函数来将消息H
发送到每个连接的节点,如下所示:示例中的错误消息来自 if 表达式中的任何子句为 true - node() 不等于node1、node2 或node3。通常的做法是通过提供
true -> 来避免这种情况。 expression
分支 - 其他语言中的else
表达式。There are a few built-in functions that can help here,
erlang:node/0
returns the name of the node it's evaluated on anderlang:nodes(connected)
returns the names of the nodes you are currently connected to.So you could write the
hash/1
function to send a messageH
to each connected node as:The error message in your example comes from none of the clauses in the if expression being true - node() is not equal to node1, node2 or node3. It's common practise to avoid that by providing a
true -> expression
branch - what would be anelse
expression in other languages.您遇到的问题是您尝试使用
if
在没有默认条件的情况下执行匹配(并且未满足您的预定义条件之一)。我不认为我曾经在 erlang 应用程序中使用过
if
,但我认为有更简单的方法可以完成您在这里尝试的操作(并且您不必重写您的添加第四个节点时的代码)。你确定你不是想写这个吗?
或者,也许是这样的:
The problem that you ran into was that you're trying to use
if
to perform a match without a default condition (and one of your predefined conditions isn't being met).I don't think I've ever used
if
in an erlang app, but I think there are much more simple ways to do what you're trying here (and you won't have to rewrite your code when you add a fourth node).Are you sure you aren't trying to write this?
Or, perhaps this: