Erlang:创建光盘架构

Erlang: create a disc schema

如果 Erlang 应用程序 myapp 需要 mnesia 运行,那么 mnesia 应该包含在其应用程序资源文件中,在键 applications 下,这样如果启动 myapp , mnesia 会自动启动——默认情况下它的节点类型是 opt_disc (OTP 18).

如果我想要一个 disc 节点怎么办?我知道我可以在命令行设置 -mnesia schema_location disc ,但这仅在模式已经存在时才有效,这意味着我应该在启动 myapp 之前执行一些初始化,是否有 "OTP-ful" 方式,而不删除 mnesia 来自 applications,以避免这种初始化?主要的objective就是把"init-then-start"变成"start".

您的 post 不正确:

... mnesia should be included in its application resource file, under key applications, so that if myapp is started, mnesia would get started automatically.

您在 .app 文件中作为 applications 键的值编写的应用程序不会自动启动,但它说它们必须在您的应用程序启动之前启动。


假设我们要创建 foo 应用程序,它依赖于 mnesia 并进行一些自定义。一种方法是在 foo_app.erl 文件中启动它:

-module(foo_app).
-behaviour(application).

-export([start/2, stop/1]).

start(_Type, _Args) ->
    mnesia:start().
    mnesia:change_table_copy_type(schema, node(), disc_copies),

    %% configure mnesia
    %% create your tables
    %% ...

    foo_sup:start_link().

stop(_State) ->
    ok.

通过这种方式,无论之前是否创建过,它都会创建 disc 模式。


注意:在这个解决方案中,如果您将 mnesia 作为 applications 键下的依赖项写入 foo.app.src 文件(在编译时将创建 foo.app),当启动 foo 应用程序时,您会得到 {error, {not_started, mnesia}}。所以你不能这样做,让你的应用程序在它的 foo_app:start/2 函数中启动它。