Optimize the emqx_zone module using persistent_term
- Don't reload the zone options for updating persistent_term is expensive - Use '{?MODULE, Zone, Key}' as the key to avoid name collision
This commit is contained in:
parent
e29cde60a9
commit
9715234626
|
@ -41,8 +41,12 @@
|
|||
, code_change/3
|
||||
]).
|
||||
|
||||
%% dummy state
|
||||
-record(state, {}).
|
||||
|
||||
-define(TAB, ?MODULE).
|
||||
-define(SERVER, ?MODULE).
|
||||
-define(KEY(Zone, Key), {?MODULE, Zone, Key}).
|
||||
|
||||
%%------------------------------------------------------------------------------
|
||||
%% APIs
|
||||
|
@ -62,7 +66,7 @@ get_env(Zone, Key) ->
|
|||
get_env(undefined, Key, Def) ->
|
||||
emqx_config:get_env(Key, Def);
|
||||
get_env(Zone, Key, Def) ->
|
||||
try persistent_term:get({Zone, Key})
|
||||
try persistent_term:get(?KEY(Zone, Key))
|
||||
catch error:badarg ->
|
||||
emqx_config:get_env(Key, Def)
|
||||
end.
|
||||
|
@ -84,7 +88,8 @@ stop() ->
|
|||
%%------------------------------------------------------------------------------
|
||||
|
||||
init([]) ->
|
||||
{ok, element(2, handle_info(reload, #{timer => undefined}))}.
|
||||
_ = do_reload(),
|
||||
{ok, #state{}}.
|
||||
|
||||
handle_call(force_reload, _From, State) ->
|
||||
_ = do_reload(),
|
||||
|
@ -95,17 +100,13 @@ handle_call(Req, _From, State) ->
|
|||
{reply, ignored, State}.
|
||||
|
||||
handle_cast({set_env, Zone, Key, Val}, State) ->
|
||||
persistent_term:put({Zone, Key}, Val),
|
||||
ok = persistent_term:put(?KEY(Zone, Key), Val),
|
||||
{noreply, State};
|
||||
|
||||
handle_cast(Msg, State) ->
|
||||
?LOG(error, "[Zone] Unexpected cast: ~p", [Msg]),
|
||||
{noreply, State}.
|
||||
|
||||
handle_info(reload, State) ->
|
||||
_ = do_reload(),
|
||||
{noreply, ensure_reload_timer(State#{timer := undefined}), hibernate};
|
||||
|
||||
handle_info(Info, State) ->
|
||||
?LOG(error, "[Zone] Unexpected info: ~p", [Info]),
|
||||
{noreply, State}.
|
||||
|
@ -121,11 +122,6 @@ code_change(_OldVsn, State, _Extra) ->
|
|||
%%------------------------------------------------------------------------------
|
||||
|
||||
do_reload() ->
|
||||
[[persistent_term:put({Zone, Key}, Val)
|
||||
|| {Key, Val} <- Opts]
|
||||
|| {Zone, Opts} <- emqx_config:get_env(zones, [])].
|
||||
[ persistent_term:put(?KEY(Zone, Key), Val)
|
||||
|| {Zone, Opts} <- emqx_config:get_env(zones, []), {Key, Val} <- Opts ].
|
||||
|
||||
ensure_reload_timer(State = #{timer := undefined}) ->
|
||||
State#{timer := erlang:send_after(timer:minutes(5), self(), reload)};
|
||||
ensure_reload_timer(State) ->
|
||||
State.
|
||||
|
|
Loading…
Reference in New Issue