如何检测从 `mix phx.server` 启动的 phoenix 应用程序?

How to detect phoenix application started from `mix phx.server`?

我在 Application.start 有一些工人 (children)。如果 phoenix app 运行 来自 mix phx.server 以外的任务(例如 mix ecto.reset),则不应启动它们。
那么,如何知道Application.start中的是mix phx.server运行的代码呢?

没有记录的方法来检查应用程序是否作为任务启动,例如。 G。因为该应用程序对生产没有 mix 依赖性。

通常,通过在项目配置中使用 :included_applications 并在需要时从 Application.start/2 when required with Application.ensure_started/2 手动加载它们来解决这种微调。对于要检查的条件,可以使用环境变量(可选地通过任务别名):

LOAD_INCLUDED=app1,app2,app3 mix ecto.reset

Application.start/2 中的某处:

"LOAD_INCLUDED"
|> System.get_env()
|> Enum.split(",")
|> Enum.map(&String.to_atom/1)
|> Application.ensure_started()

如果这些工人是您自己的工人,那就更简单了:只需调用 Kernel.++/2 并根据环境变量列出条件工人。

旁注: 在生产中,应用程序作为 OTP 版本启动,不包含 mix,因此对 mix phx.server 的显式检查毫无意义.

您可以使用 Phoenix.Endpoint.server?(otp_app, endpoint) 检查端点是否是 运行 它在给定应用程序下的服务器。以下是文档:https://hexdocs.pm/phoenix/Phoenix.Endpoint.html#server?/2