Skip to content

Commit

Permalink
feat: cache dispatch_rule
Browse files Browse the repository at this point in the history
  • Loading branch information
zhongwencool committed Jun 12, 2024
1 parent a1a08e3 commit a95bc37
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/minirest.erl
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,8 @@ start(Name, Options) ->
start(Name, ranch_opts(Options), maps:without([ranch_options], Options)).

start(Name, RanchOptions, Options) ->
init_dispatch(Name, Options),
Protocol = maps:get(protocol, Options, http),
Dispatch = merge_dispatch([], Options),
persistent_term:put(Name, Dispatch),
ProtoOpts = maps:get(protocol_options, Options, #{}),
CowboyOptions = middlewares(Options,
ProtoOpts#{
Expand All @@ -37,6 +36,17 @@ start(Name, RanchOptions, Options) ->
}),
start_listener(Protocol, Name, RanchOptions, CowboyOptions).

%% Because it is too slow to generate a fully new dispatch rules in update_dispatch/1.
%% This cache allows the listener to find the complete dispatch rules ASAP.
%% eg. emqx restarts the listener when the cluster join/leave.
init_dispatch(Name, Options) ->
case persistent_term:get(Name, undefined) of
undefined ->
Dispatch = merge_dispatch([], Options),
persistent_term:put(Name, Dispatch);
_ -> ok
end.

update_dispatch(Name) ->
[Name, _Transport, _SocketOpts, _Protocol, StartArgs]
= ranch_server:get_listener_start_args(Name),
Expand Down

0 comments on commit a95bc37

Please sign in to comment.