rebar3 服务器

This commit is contained in:
lwt
2026-05-19 11:30:21 +08:00
parent aeb18acee0
commit 03fd2da480
5187 changed files with 3670646 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
.rebar3
_*
.eunit
*.o
*.beam
*.plt
*.swp
*.swo
.erlang.cookie
ebin
log
erl_crash.dump
.rebar
logs
_build
.idea
*.iml
rebar3.crashdump
*~
+191
View File
@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2021, Anonymous <anonymous@example.org>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+9
View File
@@ -0,0 +1,9 @@
ms_tbllog
=====
An OTP application
Build
-----
$ rebar3 compile
@@ -0,0 +1,31 @@
%%%-------------------------------------------------------------------
%%% @copyright (C) 2021, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 26. 5月 2021 18:54
%%%-------------------------------------------------------------------
-include("base.hrl").
-ifndef(__MS_TBLLOG_HRL__).
-define(__MS_TBLLOG_HRL__, true).
-define(MS_TBLLOG, ms_tbllog).
%%% 打印函数
%% db_pool name
-define(DB_POOL, ms_config:get(ms_tbllog, db_update_pool_name, default)).
%% db驱动程序
-define(DB_DRIVER, ms_config:get(ms_tbllog, db_driver, 'mysql-otp')). %% 'emysql' | 'mysql-otp'
%% 缓存数据同步到数据库时间
-define(SYNC_TIME, ms_config:get(ms_tbllog, db_save_time, 120000)).
%% 缓存数据首次同步数据随机时间最小值
-define(SYNC_START_TIME, ms_config:get(ms_tbllog, db_save_start_time, 60000)).
%% 一次同步的数据量上限
-define(SYNC_COUNT, ms_config:get(ms_tbllog, db_save_count, 100)).
%% 同步时被忽略的所有字符,防止sql注入式攻击
-define(LOG_IGNORE_CHARS, [$',$",$;,$\\]).
-endif.
@@ -0,0 +1,16 @@
{application, ms_tbllog,
[{description, "An OTP application"},
{vsn, "0.1.0"},
{registered, []},
{mod, {ms_tbllog_app, []}},
{applications,
[kernel,
stdlib,
mysql_poolboy
]},
{env,[]},
{modules, []},
{licenses, ["Apache 2.0"]},
{links, []}
]}.
@@ -0,0 +1,234 @@
%%% -------------------------------------------------------------------
%%% Author : wangyalun
%%% Description : T日志模块
%%%
%%% Created : 2020-03-30
%%% -------------------------------------------------------------------
-module(ms_tbllog).
-include("base.hrl").
%% ====================================================================
%% Include files
%% ====================================================================
-include("ms_tbllog.hrl").
%% ====================================================================
%% External exports
%% ====================================================================
-export([
start/2
, start_one/1
, start_list/1
, insert/1
, insert/2
, insert_flush/1
, insert_flush/2
, hand_sync/1
]).
%% ====================================================================
%% External functions
%% ====================================================================
start(TbllogList, UpdatePrepares) ->
ok = ms_config:init_app_envs(?MS_TBLLOG),
DBDriver = ms_config:get(?MS_TBLLOG, db_driver, 'mysql-otp'),
connect_db(DBDriver, UpdatePrepares, TbllogList),
?INFO(?MODULE, "start init tbllog procceses ......", []),
start_list(TbllogList),
?INFO(?MODULE, "finish init tbllog procceses ......", []),
ok.
%%--------------------------------------------------------------------
%% @doc
%% 启动单个日志表处理进程
%% ```
%% 参数说明
%% {Table, Handler} : {表名, 表处理模块}
%% Table : 表名,标处理模块与表名同名
%% '''
%%
%% @end
%%--------------------------------------------------------------------
start_one({Table, Handler}) ->
MaxAllowedPacket = get_max_allowed_packet(),
{ok, _} = supervisor:start_child(ms_tbllog_gs_sup, [Table, Handler, erlang:ceil(MaxAllowedPacket*0.75)]),
ok;
start_one(Table) ->
start_one({Table, Table}).
%%--------------------------------------------------------------------
%% @doc
%% 启动多个日志表处理进程
%%
%% @end
%%--------------------------------------------------------------------
start_list([Elem | Rest]) ->
start_one(Elem),
start_list(Rest);
start_list([]) ->
ok.
%%--------------------------------------------------------------------
%% @doc
%% 插入数据
%% ```
%% 参数是记录,表名需为记录名;
%% 参数是Map,表名的key为'_table'
%% '''
%%
%% @end
%%--------------------------------------------------------------------
insert(Map) when is_map(Map) ->
Table = maps:get('_table', Map),
insert(Table, Map);
insert(Record) when is_tuple(Record) ->
Table = element(1, Record),
insert(Table, Record).
%%--------------------------------------------------------------------
%% @doc
%% 指定表名插入数据
%% ```
%% 参数可以是记录,也可以是Map
%% '''
%%
%% @end
%%--------------------------------------------------------------------
insert(Table, Record) ->
Handler = Table,
try
ok = Handler:check_fields_valid(Record)
catch _:ErrMsg ->
?ERROR(?MODULE, "insert error, Tab = ~p, ErrMsg = ~p, Record = ~p", [Table, ErrMsg, Record])
end,
ms_tbllog_gs:insert(Table, Record, false).
%%--------------------------------------------------------------------
%% @doc
%% 插入数据
%% ```
%% 参数是记录,表名需为记录名;
%% 参数是Map,表名的key为'_table'
%% '''
%%
%% @end
%%--------------------------------------------------------------------
insert_flush(Map) when is_map(Map) ->
Table = maps:get('_table', Map),
insert_flush(Table, Map);
insert_flush(Record) when is_tuple(Record) ->
Table = element(1, Record),
insert_flush(Table, Record).
%%--------------------------------------------------------------------
%% @doc
%% 指定表名插入数据
%% ```
%% 参数可以是记录,也可以是Map
%% '''
%%
%% @end
%%--------------------------------------------------------------------
insert_flush(Table, Record) ->
Handler = Table,
try
ok = Handler:check_fields_valid(Record)
catch _:ErrMsg ->
?ERROR(?MODULE, "insert error, Tab = ~p, ErrMsg = ~p, Record = ~p", [Table, ErrMsg, Record])
end,
ms_tbllog_gs:insert(Table, Record, true).
hand_sync(TableList) when is_list(TableList) ->
[ms_tbllog_gs:hand_sync(Table) || Table <- TableList];
hand_sync(Table) ->
ms_tbllog_gs:hand_sync(Table).
%%--------------------------------------------------------------------
%% @doc
%% 链接数据库
%%
%% @spec connect_db(DbCfgMap :: map()) -> ok.
%% @end
%%--------------------------------------------------------------------
connect_db('mysql-otp', UpdatePrepares, CacheList) ->
User = ms_config:get(?MS_TBLLOG, db_user),
Password = ms_config:get(?MS_TBLLOG, db_pass),
Host = ms_config:get(?MS_TBLLOG, db_host),
Port = ms_config:get(?MS_TBLLOG, db_port),
Database = ms_config:get(?MS_TBLLOG, db_name),
Encoding = ms_config:get(?MS_TBLLOG, db_encoding),
UpdatePoolName = ms_config:get(?MS_TBLLOG, db_update_pool_name, undefined),
UpdatePoolSize = ms_config:get(?MS_TBLLOG, db_update_pool_size, 10),
?INFO(?MODULE, "connect_db,
user : ~s,
pass : ~s,
host : ~s,
port : ~p,
database : ~s,
encoding : ~p,
update_pool_name : ~p,
update_pool_size : ~p ",
[User, Password, Host, Port, Database, Encoding, UpdatePoolName, UpdatePoolSize]),
%% mysql连接信息
MysqlOptions = [
{host, Host},
{port, Port},
{user, User},
{password, Password},
{database, Database},
{keep_alive, true},
{log_slow_queries, true}
],
#{ level:=OldLevel } = logger:get_primary_config(),
try
%% mysql底层用到了logger输出日志,设置error,减少不必要的输出
logger:set_primary_config(level, error),
{ok, _} = mysql_poolboy:add_pool(ms_tbllog_tmp, [{size, 1}, {max_overflow, 0}], lists:keydelete(database, 1, MysqlOptions)),
ok = mysql_poolboy:query(ms_tbllog_tmp, io_lib:format("CREATE DATABASE IF NOT EXISTS ~s;", [Database])),
ok = supervisor:terminate_child(mysql_poolboy_sup, ms_tbllog_tmp),
%% TODO mysql-otp初始化时传入了prepare,所以需要表预先创建好,这个写法可能不太好,暂时先这样
{ok, _} = mysql_poolboy:add_pool(ms_tbllog_create_tmp, [{size, 1}, {max_overflow, 0}], MysqlOptions),
[
begin
Handler:create(ms_tbllog_create_tmp),
Handler:do_table_changed(ms_tbllog_create_tmp)
end
|| {_, Handler} <- CacheList
],
ok = supervisor:terminate_child(mysql_poolboy_sup, ms_tbllog_create_tmp)
catch ErrCode:ErrMsg:Trace ->
?ERROR(?MODULE, "CHECK_TBLLOG_DATABASE_ERROR, ErrCode = ~w, ErrMsg = ~w, Trace = ~w", [ErrCode, ErrMsg, Trace]),
ok
after
logger:set_primary_config(level, OldLevel)
end,
?IF(UpdatePoolName /= undefined,
{ok, _} = mysql_poolboy:add_pool(
UpdatePoolName,
[{size, UpdatePoolSize}, {max_overflow, 0}],
[{prepare, UpdatePrepares} | MysqlOptions]
)
),
ok.
get_max_allowed_packet() ->
get_max_allowed_packet(ms_config:get(?MS_TBLLOG, db_driver, 'mysql-otp')).
get_max_allowed_packet('mysql-otp') ->
case ms_config:get(?MS_TBLLOG, db_update_pool_name, undefined) of
undefined ->
1024*1024;
UpdatePool ->
{ok, _, [[MaxAllowedPacket]]} = mysql_poolboy:query(UpdatePool, "SELECT @@max_allowed_packet"),
MaxAllowedPacket
end;
get_max_allowed_packet(_) ->
1024*1024.
@@ -0,0 +1,32 @@
%%%-------------------------------------------------------------------
%% @doc ms_tbllog public API
%% @end
%%%-------------------------------------------------------------------
-module(ms_tbllog_app).
-include("base.hrl").
-behaviour(application).
-export([start/2, stop/1, config_change/3]).
-include("ms_tbllog.hrl").
start(_StartType, _StartArgs) ->
ms_tbllog_sup:start_link().
stop(_State) ->
ok.
%% rebar3热更会用版本内的sys.config的配置替换运行的代码,导致热更的application的envs被替换
%% 游戏各个服配置不一样,难以在打升级包的时候就把sys.config定义好
%% 通常情况热更的时候,这些配置就会被替换成空失效
%% config_change是热更时替换sys.config数据后调用被热更配置的app,所以在这里将app的ets回写到ac_tab
%% 注意:不能用application:set_env来处理,call会导致死锁,因为这个处理是在application_controller进程执行
config_change(_Changed, _New, _Removed) ->
%% 统一由启动cache的app去修改app的环境变量
?INFO(?MODULE, "ms_cache hotfix config change", []),
ok.
%% internal functions
@@ -0,0 +1,237 @@
%%% -------------------------------------------------------------------
%%% Author : wangyalun
%%% Description : T日志模块
%%%
%%% Created : 2020-03-30
%%% -------------------------------------------------------------------
-module(ms_tbllog_gs).
-include("base.hrl").
-behaviour(gen_server).
%% ====================================================================
%% Include files
%% ====================================================================
-include("ms_tbllog.hrl").
%% ====================================================================
%% Define Macro
%% ====================================================================
-define(SERVER(Table), list_to_atom("ms_tbllog_" ++ atom_to_list(Table))).
-define(DATA_NODE,
case ms_config:get(?MS_TBLLOG, data_node, undefined) of
undefined ->
erlang:node();
CenterNode ->
CenterNode
end
).
%% ====================================================================
%% External exports
%% ====================================================================
-export([
start_link/3
, insert/3
, hand_sync/1
, recreate/1
]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
%% ====================================================================
%% External functions
%% ====================================================================
start_link(Table, Handler, BatchLen) ->
FirstTime = ?SYNC_START_TIME + rand:uniform(?SYNC_TIME),
gen_server:start_link({local, ?SERVER(Table)}, ?MODULE, [Table, Handler, FirstTime, BatchLen], []).
insert(Table, Record, SaveNow) ->
gen_server:cast({?SERVER(Table), ?DATA_NODE}, {insert, Record, SaveNow}).
%% 手动同步数据
hand_sync(Table) ->
gen_server:cast({?SERVER(Table), ?DATA_NODE}, hand_sync).
%% 清空并重新创建表
recreate(Table) ->
gen_server:cast({?SERVER(Table), ?DATA_NODE}, recreate).
%% ====================================================================
%% Server functions
%% ====================================================================
%% --------------------------------------------------------------------
%% Function: init/1
%% Description: Initiates the server
%% Returns: {ok, State} |
%% {ok, State, Timeout} |
%% ignore |
%% {stop, Reason}
%% --------------------------------------------------------------------
init([Table, Handler, FirstTime, BatchLen]) ->
?DEBUG(?MODULE, "~p init, handler = ~p", [?SERVER(Table), Handler]),
erlang:process_flag(trap_exit, true),
erlang:send(self(), {init, FirstTime}, [noconnect]),
{ok, #{table => Table, handler => Handler, batch_len => BatchLen}}.
%% --------------------------------------------------------------------
%% Function: handle_call/3
%% Description: Handling call messages
%% Returns: {reply, Reply, State} |
%% {reply, Reply, State, Timeout} |
%% {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, Reply, State} | (terminate/2 is called)
%% {stop, Reason, State} (terminate/2 is called)
%% --------------------------------------------------------------------
handle_call(Msg, From, #{table := Table} = State) ->
try
do_call(Msg, From, State)
catch _ErrCode:ErrMsg:Trace ->
?ERROR(Table, "handle call: Msg = ~p, ErrMsg = ~p, Trace = ~p", [Msg, ErrMsg, Trace]),
{reply, ok, State}
end.
%% --------------------------------------------------------------------
%% Function: handle_cast/2
%% Description: Handling cast messages
%% Returns: {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State} (terminate/2 is called)
%% --------------------------------------------------------------------
handle_cast(Msg, #{table := Table} = State) ->
try
do_cast(Msg, State)
catch _ErrCode:ErrMsg:Trace ->
?ERROR(Table, "handle cast: Msg = ~p, ErrMsg = ~p, Trace = ~p", [Msg, ErrMsg, Trace]),
{noreply, State}
end.
%% --------------------------------------------------------------------
%% Function: handle_info/2
%% Description: Handling all non call/cast messages
%% Returns: {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State} (terminate/2 is called)
%% --------------------------------------------------------------------
handle_info(Msg, #{table := Table} = State) ->
try
do_info(Msg, State)
catch _ErrCode:ErrMsg:Trace ->
?ERROR(Table, "handle info: Msg = ~p, ErrMsg = ~p, Trace = ~p", [Msg, ErrMsg, Trace]),
{noreply, State}
end.
%% --------------------------------------------------------------------
%% Function: terminate/2
%% Description: Shutdown the server
%% Returns: any (ignored by gen_server)
%% --------------------------------------------------------------------
terminate(Reason, #{table := Table, handler := Handler, batch_len := BatchLen}) ->
?INFO(Table, "~p terminate, Reason=~p", [?SERVER(Table), Reason]),
sync_all_to_db(get_record_list(), Handler, BatchLen),
ok.
%% --------------------------------------------------------------------
%% Func: code_change/3
%% Purpose: Convert process state when code is changed
%% Returns: {ok, NewState}
%% --------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% --------------------------------------------------------------------
%%% callback functions
%% --------------------------------------------------------------------
do_call(_Request, _From, State) ->
{reply, ok, State}.
do_cast({insert, MapOrRec, SaveNow}, #{handler := Handler, batch_len := BatchLen} = State) ->
Record = Handler:map_to_record(MapOrRec),
OldList = get_record_list(),
{NewRecordList, NewRecordCount} =
case Handler:key_poses() of
[KeyPos] ->
Val = erlang:element(KeyPos, Record),
case lists:keyfind(Val, KeyPos, OldList) of
false ->
{[Record | OldList], get_record_count() + 1};
_ ->
?INFO(?MODULE, "Table = ~p, KeyPos = ~p, Val = ~p", [erlang:element(1, Record), KeyPos, Val]),
{lists:keyreplace(Val, KeyPos, OldList, Record), get_record_count()}
end;
_ -> %% todo 没有主键或多主键的直接插入,暂时没有多主键,先不支持;如果后面有多主键的,需要像cache那样增加一个'_id'的虚拟主键来处理
{[Record | OldList], get_record_count() + 1}
end,
%% [Handler:map_to_record(Record) | get_record_list()],% todo 生成的tbllog_xxx.erl文件导出主键,有主键的表进行值替换
%% NewRecordCount = get_record_count() + 1,
case SaveNow orelse NewRecordCount >= ?SYNC_COUNT of
true ->
sync_all_to_db(NewRecordList, Handler, BatchLen);
false ->
set_record_list(NewRecordList),
set_record_count(NewRecordCount)
end,
{noreply, State};
do_cast(hand_sync, #{table := Table, handler := Handler, batch_len := BatchLen} = State) ->
?INFO(Table, "start_hand_sync, Table = ~p", [Table]),
sync_all_to_db(get_record_list(), Handler, BatchLen),
{noreply, State};
do_cast(recreate, #{handler := Handler} = State) ->
Handler:recreate(?DB_POOL),
{noreply, State}.
do_info({init, FirstTime}, State) ->
erlang:send_after(?SYNC_TIME + FirstTime, self(), sync),
{noreply, State};
do_info(sync, #{handler := Handler, batch_len := BatchLen} = State) ->
erlang:send_after(?SYNC_TIME, self(), sync),
sync_all_to_db(get_record_list(), Handler, BatchLen),
{noreply, State}.
%% --------------------------------------------------------------------
%%% Internal functions
%% --------------------------------------------------------------------
%% 批量同步日志到数据库
sync_all_to_db(RecordList, Handler, BatchLen) ->
BeginSyncTime = erlang:system_time(seconds),
set_record_list([]),
set_record_count(0),
%% 插入的时候头部插入,入库的时候先反序,保证数据的顺序是正确的
Handler:batch_insert(?DB_POOL, lists:reverse(RecordList), BatchLen),
EndSyncTime = erlang:system_time(seconds),
SyncNum = get_record_count(),
case SyncNum > 0 of
true ->
?INFO(?MODULE, "sync_time_info = ~p", [{Handler, SyncNum, EndSyncTime - BeginSyncTime}]);
false ->
ok
end.
%% 获取待同步数据
get_record_list() ->
case erlang:get(record_list) of
undefined ->
[];
RecordList ->
RecordList
end.
%% 设置待同步数据
set_record_list(RecordList) ->
erlang:put(record_list, RecordList).
%% 获取待同步数据的数量
get_record_count() ->
case erlang:get(record_count) of
undefined ->
0;
Count ->
Count
end.
%% 设置待同步数据的数量
set_record_count(Count) ->
erlang:put(record_count, Count).
@@ -0,0 +1,60 @@
%%%-------------------------------------------------------------------
%%% @copyright (C) 2021, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 26. 5月 2021 17:47
%%%-------------------------------------------------------------------
-module(ms_tbllog_gs_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%%===================================================================
%%% API functions
%%%===================================================================
%% @doc Starts the supervisor
-spec(start_link() -> {ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
%% @private
%% @doc Whenever a supervisor is started using supervisor:start_link/[2,3],
%% this function is called by the new process to find out about
%% restart strategy, maximum restart frequency and child
%% specifications.
-spec(init(Args :: term()) ->
{ok, {SupFlags :: {RestartStrategy :: supervisor:strategy(),
MaxR :: non_neg_integer(), MaxT :: non_neg_integer()},
[ChildSpec :: supervisor:child_spec()]}}
| ignore | {error, Reason :: term()}).
init([]) ->
MaxRestarts = 5,
MaxSecondsBetweenRestarts = 10,
SupFlags = #{strategy => simple_one_for_one,
intensity => MaxRestarts,
period => MaxSecondsBetweenRestarts},
AChild = #{id => 'ms_tbllog_gs',
start => {'ms_tbllog_gs', start_link, []},
restart => permanent,
shutdown => infinity,
type => worker,
modules => ['ms_tbllog_gs']},
{ok, {SupFlags, [AChild]}}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
@@ -0,0 +1,44 @@
%%%-------------------------------------------------------------------
%% @doc ms_tbllog top level supervisor.
%% @end
%%%-------------------------------------------------------------------
-module(ms_tbllog_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%% sup_flags() = #{strategy => strategy(), % optional
%% intensity => non_neg_integer(), % optional
%% period => pos_integer()} % optional
%% child_spec() = #{id => child_id(), % mandatory
%% start => mfargs(), % mandatory
%% restart => restart(), % optional
%% shutdown => shutdown(), % optional
%% type => worker(), % optional
%% modules => modules()} % optional
init([]) ->
MaxRestarts = 5,
MaxSecondsBetweenRestarts = 10,
SupFlags = #{strategy => one_for_one,
intensity => MaxRestarts,
period => MaxSecondsBetweenRestarts},
AChild = #{id => 'ms_tbllog_gs_sup',
start => {'ms_tbllog_gs_sup', start_link, []},
restart => permanent,
shutdown => infinity,
type => supervisor,
modules => ['ms_tbllog_gs_sup']},
{ok, {SupFlags, [AChild]}}.
%% internal functions