Add emqx_trie:empty/0 and optimize match_routes/1

This commit is contained in:
Feng Lee 2018-12-24 13:08:20 +08:00 committed by Feng Lee
parent 981d785c06
commit 0c418581b2
2 changed files with 13 additions and 3 deletions

View File

@ -101,9 +101,13 @@ do_add_route(Topic, Dest) when is_binary(Topic) ->
%% @doc Match routes %% @doc Match routes
-spec(match_routes(emqx_topic:topic()) -> [emqx_types:route()]). -spec(match_routes(emqx_topic:topic()) -> [emqx_types:route()]).
match_routes(Topic) when is_binary(Topic) -> match_routes(Topic) when is_binary(Topic) ->
case emqx_trie:empty() of
true -> lookup_routes(Topic);
false ->
%% Optimize: routing table will be replicated to all router nodes. %% Optimize: routing table will be replicated to all router nodes.
Matched = mnesia:ets(fun emqx_trie:match/1, [Topic]), Matched = mnesia:ets(fun emqx_trie:match/1, [Topic]),
lists:append([lookup_routes(To) || To <- [Topic | Matched]]). lists:append([lookup_routes(To) || To <- [Topic | Matched]])
end.
-spec(lookup_routes(emqx_topic:topic()) -> [emqx_types:route()]). -spec(lookup_routes(emqx_topic:topic()) -> [emqx_types:route()]).
lookup_routes(Topic) -> lookup_routes(Topic) ->

View File

@ -24,6 +24,7 @@
%% Trie APIs %% Trie APIs
-export([insert/1, match/1, lookup/1, delete/1]). -export([insert/1, match/1, lookup/1, delete/1]).
-export([empty/0]).
%% Mnesia tables %% Mnesia tables
-define(TRIE, emqx_trie). -define(TRIE, emqx_trie).
@ -100,6 +101,11 @@ delete(Topic) when is_binary(Topic) ->
[] -> ok [] -> ok
end. end.
%% @doc Is the trie empty?
-spec(empty() -> boolean()).
empty() ->
ets:info(?TRIE, size) == 0.
%%------------------------------------------------------------------------------ %%------------------------------------------------------------------------------
%% Internal functions %% Internal functions
%%------------------------------------------------------------------------------ %%------------------------------------------------------------------------------