gpt4 book ai didi

Elixir:主管、GenServer 和应用程序之间的区别

转载 作者:行者123 更新时间:2023-12-03 14:02:01 26 4
gpt4 key购买 nike

我正在练习这个例子。
https://github.com/kwmiebach/how-to-elixir-supervisor

我按照说明进行操作并了解它是如何工作的,但我无法理解 Supervisor、GenServer 和 Application 究竟有何不同。

有人可以解释这三个有何不同以及何时应该使用它们吗?

最佳答案

首先,这些都是“OTP 设计原则”(并由标准库支持),它们都是基本 Erlang 原语(如进程)之上的包装器(或者更好的说法是抽象)。这意味着它们不是在 Erlang 中编程的唯一方法(因此是 Elixir),但它们被社区共享,并得到了数十年实战考验的现实世界系统的支持。所以你也应该使用它们。
GenServer通常被认为是使用 Elixir 实现的应用程序的基本运行时构建 block 。尽管实际上它是对较低级别 Erlang Process 原语的封装,但是,GenServer在标准界面中提供了许多高级功能,例如调试和跟踪。基本上,您通常会使用(很多)GenServer在您的应用程序中管理状态和“做实际工作”。

Supervisor , as the documentation suggests :

A supervisor is a process which supervises other processes, which we refer to as child processes. Supervisors are used to build a hierarchical process structure called a supervision tree.



所以从某种意义上说,它“管理” GenServer s,还有其他 Supervisor s(以及其他 Erlang Process 抽象,如果它们实现了正确的接口(interface))。您通常不会在 Supervisor 中添加任何自定义逻辑。模块,部分原因是它们的作用非常集中——只管理子进程的生命周期。但也使其不易出错(由您的更改引入)。

换一种说法, Supervisor不会为您的应用程序做任何实际的“工作”,它只是用于“布局”系统的架构。

与其他人相比, Application不一定是“运行时问题”, as the Erlang documentation suggests :

... make the code into an application, that is, a component that can be started and stopped as a unit, and which can also be reused in other systems.



所以 Application实际上是将东西捆绑到一个“单元”中,而实际系统通常由许多这样的单元组成-例如,每当您运行一些 Elixir 代码时,还有一个 "elixir" Application它运行多个进程,例如 elixir_code_server :

Elixir Runtime

更重要的是, Application是在 OTP 设计原则中共享(重用)代码的方式。当您定义一个应用程序时,它可以有一个“root supervisor”,它与应用程序一起启动。或者它也可以只包含功能代码,根本不运行任何进程,例如 a JSON library .无论哪种方式,要跨不同系统重用代码,都需要将它们打包到 Application s。

最后,我建议阅读一下: https://ferd.ca/the-zen-of-erlang.html它解释了(至少对我而言)我们如何从基本(Erlang)流程到监督者(和监督树)以及一些 OTP 应用程序。 (以及我们应该如何在 BEAM 中进行编程)

关于Elixir:主管、GenServer 和应用程序之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53358893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com