Skip to content
This repository was archived by the owner on Nov 17, 2020. It is now read-only.

Commit d3ee921

Browse files
Merge pull request #216 from velimir/convert-cache
cache topic translation results (cherry picked from commit 3180bcc)
1 parent a92e3dd commit d3ee921

File tree

1 file changed

+34
-8
lines changed

1 file changed

+34
-8
lines changed

src/rabbit_mqtt_util.erl

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,25 +28,51 @@
2828
get_topic_translation_funs/0
2929
]).
3030

31+
-define(MAX_TOPIC_TRANSLATION_CACHE_SIZE, 12).
32+
3133
subcription_queue_name(ClientId) ->
3234
Base = "mqtt-subscription-" ++ ClientId ++ "qos",
3335
{list_to_binary(Base ++ "0"), list_to_binary(Base ++ "1")}.
3436

37+
cached(CacheName, Fun, Arg) ->
38+
Cache =
39+
case get(CacheName) of
40+
undefined ->
41+
[];
42+
Other ->
43+
Other
44+
end,
45+
case lists:keyfind(Arg, 1, Cache) of
46+
{_, V} ->
47+
V;
48+
false ->
49+
V = Fun(Arg),
50+
CacheTail = lists:sublist(Cache, ?MAX_TOPIC_TRANSLATION_CACHE_SIZE - 1),
51+
put(CacheName, [{Arg, V} | CacheTail]),
52+
V
53+
end.
54+
55+
to_amqp(T0) ->
56+
T1 = string:replace(T0, "/", ".", all),
57+
T2 = string:replace(T1, "+", "*", all),
58+
erlang:iolist_to_binary(T2).
59+
60+
to_mqtt(T0) ->
61+
T1 = string:replace(T0, "*", "+", all),
62+
T2 = string:replace(T1, ".", "/", all),
63+
erlang:iolist_to_binary(T2).
64+
3565
%% amqp mqtt descr
3666
%% * + match one topic level
3767
%% # # match multiple topic levels
3868
%% . / topic level separator
3969
get_topic_translation_funs() ->
4070
SparkplugB = env(sparkplug),
41-
ToAmqpFun = fun(T0) ->
42-
T1 = string:replace(T0, "/", ".", all),
43-
T2 = string:replace(T1, "+", "*", all),
44-
erlang:iolist_to_binary(T2)
71+
ToAmqpFun = fun(Topic) ->
72+
cached(mta_cache, fun to_amqp/1, Topic)
4573
end,
46-
ToMqttFun = fun(T0) ->
47-
T1 = string:replace(T0, "*", "+", all),
48-
T2 = string:replace(T1, ".", "/", all),
49-
erlang:iolist_to_binary(T2)
74+
ToMqttFun = fun(Topic) ->
75+
cached(atm_cache, fun to_mqtt/1, Topic)
5076
end,
5177
{M2AFun, A2MFun} = case SparkplugB of
5278
true ->

0 commit comments

Comments
 (0)