Remove the unnecessary transactions to optimize session management

This commit is contained in:
Feng Lee 2017-12-01 17:16:59 +08:00
parent d2a4e2c615
commit c308037b1a
2 changed files with 15 additions and 23 deletions

View File

@ -156,7 +156,7 @@ handle_call({start_session, false, {ClientId, Username}, ClientPid}, _From, Stat
{reply, {ok, SessPid, true}, State};
{error, Erorr} ->
{reply, {error, Erorr}, State}
end
end
end;
%% Transient Session
@ -183,16 +183,14 @@ handle_cast(Msg, State) ->
handle_info({'DOWN', MRef, process, DownPid, _Reason}, State) ->
case dict:find(MRef, State#state.monitors) of
{ok, ClientId} ->
mnesia:transaction(fun() ->
case mnesia:wread({mqtt_session, ClientId}) of
[] ->
ok;
[Sess = #mqtt_session{sess_pid = DownPid}] ->
mnesia:delete_object(mqtt_session, Sess, write);
[_Sess] ->
ok
end
end),
case mnesia:dirty_read({mqtt_session, ClientId}) of
[] ->
ok;
[Sess = #mqtt_session{sess_pid = DownPid}] ->
mnesia:dirty_delete_object(Sess);
[_Sess] ->
ok
end,
{noreply, erase_monitor(MRef, State), hibernate};
error ->
lager:error("MRef of session ~p not found", [DownPid]),
@ -283,15 +281,14 @@ destroy_session(Session = #mqtt_session{client_id = ClientId, sess_pid = SessPi
remove_session(Session);
%% Remote node
destroy_session(Session = #mqtt_session{client_id = ClientId,
sess_pid = SessPid}) ->
destroy_session(Session = #mqtt_session{client_id = ClientId, sess_pid = SessPid}) ->
Node = node(SessPid),
case rpc:call(Node, emqttd_session, destroy, [SessPid, ClientId]) of
ok ->
remove_session(Session);
{badrpc, nodedown} ->
?LOG(error, "Node '~s' down", [Node], Session),
remove_session(Session);
remove_session(Session);
{badrpc, Reason} ->
?LOG(error, "Failed to destory ~p on remote node ~p for ~s",
[SessPid, Node, Reason], Session),
@ -299,10 +296,7 @@ destroy_session(Session = #mqtt_session{client_id = ClientId,
end.
remove_session(Session) ->
case mnesia:transaction(fun mnesia:delete_object/1, [Session]) of
{atomic, ok} -> ok;
{aborted, Error} -> {error, Error}
end.
mnesia:dirty_delete_object(Session).
monitor_session(ClientId, SessPid, State = #state{monitors = Monitors}) ->
MRef = erlang:monitor(process, SessPid),

View File

@ -24,8 +24,6 @@
-include("emqttd.hrl").
-define(SM, emqttd_sm).
-define(HELPER, emqttd_sm_helper).
%% API
@ -44,11 +42,11 @@ init([]) ->
%% Helper
StatsFun = emqttd_stats:statsfun('sessions/count', 'sessions/max'),
Helper = {?HELPER, {?HELPER, start_link, [StatsFun]},
permanent, 5000, worker, [?HELPER]},
permanent, 5000, worker, [?HELPER]},
%% SM Pool Sup
MFA = {?SM, start_link, []},
PoolSup = emqttd_pool_sup:spec([?SM, hash, erlang:system_info(schedulers), MFA]),
MFA = {emqttd_sm, start_link, []},
PoolSup = emqttd_pool_sup:spec([emqttd_sm, hash, erlang:system_info(schedulers), MFA]),
{ok, {{one_for_all, 10, 3600}, [Helper, PoolSup]}}.