Przeglądaj źródła

perf: cache gateway definitions in persistent-term

zmstone 1 rok temu
rodzic
commit
226612265f

+ 4 - 8
apps/emqx_gateway/src/emqx_gateway_cm_registry.erl

@@ -96,19 +96,15 @@ record(ClientId, ChanPid) ->
     #channel{chid = ClientId, pid = ChanPid}.
 
 get_connected_client_count() ->
+    %% NOTE: this call is very slow
     Gatewyas = emqx_gateway_utils:find_gateway_definitions(),
     Fun = fun(#{name := Name}, Acc) ->
         Tab = tabname(Name),
-        case ets:whereis(Tab) of
+        case ets:info(Tab, size) of
             undefined ->
                 Acc;
-            _ ->
-                case ets:info(Tab, size) of
-                    undefined ->
-                        Acc;
-                    Size ->
-                        Acc + Size
-                end
+            Size ->
+                Acc + Size
         end
     end,
     lists:foldl(Fun, 0, Gatewyas).

+ 16 - 0
apps/emqx_gateway/src/emqx_gateway_utils.erl

@@ -704,6 +704,12 @@ default_subopts() ->
 
 -spec find_gateway_definitions() -> list(gateway_def()).
 find_gateway_definitions() ->
+    read_pt_populate_if_missing(
+        emqx_gateways,
+        fun do_find_gateway_definitions/0
+    ).
+
+do_find_gateway_definitions() ->
     lists:flatmap(
         fun(App) ->
             lists:flatmap(fun gateways/1, find_attrs(App, gateway))
@@ -711,6 +717,16 @@ find_gateway_definitions() ->
         ?GATEWAYS
     ).
 
+read_pt_populate_if_missing(Key, Fn) ->
+    case persistent_term:get(Key, no_value) of
+        no_value ->
+            Value = {value, Fn()},
+            _ = persistent_term:put(Key, Value),
+            Value;
+        {value, Value} ->
+            Value
+    end.
+
 -spec find_gateway_definition(atom()) -> {ok, map()} | {error, term()}.
 find_gateway_definition(Name) ->
     find_gateway_definition(Name, ?GATEWAYS).