From a95bc37de0f975ad0239a54ef10a014096a02f41 Mon Sep 17 00:00:00 2001 From: zhongwencool Date: Wed, 12 Jun 2024 20:29:03 +0800 Subject: [PATCH] feat: cache dispatch_rule --- src/minirest.erl | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/minirest.erl b/src/minirest.erl index 8192aad..a89da53 100644 --- a/src/minirest.erl +++ b/src/minirest.erl @@ -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#{ @@ -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),