Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- hello_erlang.app.src
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- {application, hello_erlang, [
- {description, ""},
- {vsn, "0.1.0"},
- {id, "git"},
- {modules, []},
- {registered, []},
- {applications, [
- kernel,
- stdlib,
- cowboy,
- mongodb,
- jiffy
- ]},
- {mod, {hello_erlang_app, []}},
- {env,
- [
- {
- mongodb_pools,
- [
- {
- mg_pool1,
- [
- {size, 10},
- {max_overflow, 20}
- ],
- [
- {hostname, "127.0.0.1"},
- {database, "user"},
- {username, "zhk"},
- {password, "zhk"}
- ]
- }
- ]
- }
- ]
- }
- ]}.
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- db_mongo_handler.erl
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- %%%-------------------------------------------------------------------
- %%% @author zhouhuakang
- %%% @copyright (C) 2015, <COMPANY>
- %%% @doc
- %%%
- %%% @end
- %%% Created : 27. Jan 2015 10:44 AM
- %%%-------------------------------------------------------------------
- -module(db_mongo_handler).
- -author("zhouhuakang").
- -behaviour(gen_server).
- %% API
- -export([start_link/1]).
- %% gen_server callbacks
- -export([init/1,
- handle_call/3,
- handle_cast/2,
- handle_info/2,
- terminate/2,
- code_change/3]).
- -define(SERVER, ?MODULE).
- -record(state, {connection}).
- %%%===================================================================
- %%% API
- %%%===================================================================
- %%--------------------------------------------------------------------
- %% @doc
- %% Starts the server
- %%
- %% @end
- %%--------------------------------------------------------------------
- -spec(start_link(Args :: list()) ->
- {ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
- start_link(Args) ->
- gen_server:start_link(?MODULE, Args, []).
- %%%===================================================================
- %%% gen_server callbacks
- %%%===================================================================
- %%--------------------------------------------------------------------
- %% @private
- %% @doc
- %% Initializes the server
- %%
- %% @spec init(Args) -> {ok, State} |
- %% {ok, State, Timeout} |
- %% ignore |
- %% {stop, Reason}
- %% @end
- %%--------------------------------------------------------------------
- -spec(init(Args :: term()) ->
- {ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
- {stop, Reason :: term()} | ignore).
- init(Args) ->
- Hostname = proplists:get_value(hostname, Args),
- Database = proplists:get_value(database, Args),
- %% no user and pass for the moment
- Username = proplists:get_value(username, Args),
- Password = proplists:get_value(password, Args),
- {ok, Connection} = mongo:connect(Hostname, 27017, Database),
- io:format("***************************Debug*********************************~n
- Module:~p ~n Line:~p ~n Database Connection:~p ~n", [?MODULE, ?LINE, Connection]),
- %% user-specific setup
- SetupFun = proplists:get_value(setup, Args),
- case SetupFun of
- undefined -> ok;
- {Mod, Fun} -> erlang:apply(Mod, Fun, [Connection, Args])
- end,
- {ok, #state{connection = Connection}}.
- %%--------------------------------------------------------------------
- %% @private
- %% @doc
- %% Handling call messages
- %%
- %% @end
- %%--------------------------------------------------------------------
- -spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
- State :: #state{}) ->
- {reply, Reply :: term(), NewState :: #state{}} |
- {reply, Reply :: term(), NewState :: #state{}, timeout() | hibernate} |
- {noreply, NewState :: #state{}} |
- {noreply, NewState :: #state{}, timeout() | hibernate} |
- {stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
- {stop, Reason :: term(), NewState :: #state{}}).
- handle_call({get_user, {Collection, Selector}}, _From, #state{connection = Connection} = State) ->
- io:format("***************************Debug*********************************~n
- Module:~p ~n Line:~p ~n Handle_call Connection:~p ~n Collection:~p ~n
- Selector:~p ~n Connection is is_pid()? ~p ~n Collection is binary()? ~p ~n",
- [?MODULE, ?LINE, Connection, Collection, Selector, is_pid(Connection), is_binary(Collection)]),
- Cursor = mongo:find(Connection, Collection, Selector ),
- io:format("***************************Debug*********************************~n Module:~p ~n Line:~p ~n
- Cursor:~p ~n", [?MODULE, ?LINE, Cursor]),
- Result = mc_cursor:rest(Cursor),
- [Head | _] = Result,
- {_, _, _, NameValue, _, AgeValue} = Head,
- io:format("***************************Debug*********************************~n Module:~p ~n Line:~p ~n
- NameValue:~p ~n AgeValue:~p ~n ", [?MODULE, ?LINE, NameValue, AgeValue]),
- BackData = binary_to_list(<<NameValue/bits, <<":">>/bits, AgeValue/bits>>),
- {reply, BackData, State}.
- %%--------------------------------------------------------------------
- %% @private
- %% @doc
- %% Handling cast messages
- %%
- %% @end
- %%--------------------------------------------------------------------
- -spec(handle_cast(Request :: term(), State :: #state{}) ->
- {noreply, NewState :: #state{}} |
- {noreply, NewState :: #state{}, timeout() | hibernate} |
- {stop, Reason :: term(), NewState :: #state{}}).
- handle_cast(_Request, State) ->
- {noreply, State}.
- %%--------------------------------------------------------------------
- %% @private
- %% @doc
- %% Handling all non call/cast messages
- %%
- %% @spec handle_info(Info, State) -> {noreply, State} |
- %% {noreply, State, Timeout} |
- %% {stop, Reason, State}
- %% @end
- %%--------------------------------------------------------------------
- -spec(handle_info(Info :: timeout() | term(), State :: #state{}) ->
- {noreply, NewState :: #state{}} |
- {noreply, NewState :: #state{}, timeout() | hibernate} |
- {stop, Reason :: term(), NewState :: #state{}}).
- handle_info(_Info, State) ->
- {noreply, State}.
- %%--------------------------------------------------------------------
- %% @private
- %% @doc
- %% This function is called by a gen_server when it is about to
- %% terminate. It should be the opposite of Module:init/1 and do any
- %% necessary cleaning up. When it returns, the gen_server terminates
- %% with Reason. The return value is ignored.
- %%
- %% @spec terminate(Reason, State) -> void()
- %% @end
- %%--------------------------------------------------------------------
- -spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
- State :: #state{}) -> term()).
- terminate(_Reason, _State) ->
- ok.
- %%--------------------------------------------------------------------
- %% @private
- %% @doc
- %% Convert process state when code is changed
- %%
- %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState}
- %% @end
- %%--------------------------------------------------------------------
- -spec(code_change(OldVsn :: term() | {down, term()}, State :: #state{},
- Extra :: term()) ->
- {ok, NewState :: #state{}} | {error, Reason :: term()}).
- code_change(_OldVsn, State, _Extra) ->
- {ok, State}.
- %%%===================================================================
- %%% Internal functions
- %%%===================================================================
- get_user(Name, Connection, Req) ->
- Selector = {Name, <<"undefined">>},
- Collection = <<"user">>,
- Cursor = mongo:find(Connection, Collection, Selector),
- Result = mc_cursor:rest(Cursor),
- [Head | _] = Result,
- {_, _, _, NameValue, _, AgeValue} = Head,
- BackData = binary_to_list(<<NameValue/bits, <<":">>/bits, AgeValue/bits>>).
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- hello_erlang_app.erl
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- -module(hello_erlang_app).
- -behaviour(application).
- -export([start/2]).
- -export([stop/1]).
- start(_Type, _Args) ->
- %% init cowboy
- Dispatch = cowboy_router:compile([
- {'_', [{"/user/[:user_name]", hello_handler, []}]}
- ]),
- cowboy:start_http(my_http_listener, 100, [{port, 8080}],
- [{env, [{dispatch, Dispatch}]}]
- ),
- io:format("Cowboy inited Line 22 ~n "),
- hello_erlang_sup:start_link().
- stop(_State) ->
- ok.
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- hello_erlang_sup.erl
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- -module(hello_erlang_sup).
- -behaviour(supervisor).
- -export([start_link/0]).
- -export([init/1]).
- start_link() ->
- supervisor:start_link({local, ?MODULE}, ?MODULE, []).
- init([]) ->
- %% init mongodb
- {ok, Pools} = application:get_env(hello_erlang, mongodb_pools),
- io:format("**********************************************************************Pools is ~n ~p ~n ", [Pools]),
- PoolSpecs =
- lists:map(
- fun({Name, SizeArgs, WorkerArgs}) ->
- PoolArgs = [{name, {local, Name}}, {worker_module, db_mongo_handler}] ++ SizeArgs,
- io:format("****************************************************************Name is ~n ~p ~n ", [Name]),
- io:format("****************************************************************SizeArgs is ~n ~p ~n ", [SizeArgs]),
- io:format("****************************************************************WorkerArgs is ~n ~p ~n ", [WorkerArgs]),
- poolboy:child_spec(Name, PoolArgs, WorkerArgs)
- end,
- Pools),
- io:format("**********************************************************************PoolsSpecs:re ~n ~p ~n", [PoolSpecs]),
- io:format("**********************************************************************Poolboy has exited: ~n ~p ~n", [poolboy:module_info()]),
- {ok, {{one_for_one, 10, 10}, PoolSpecs}}.
- %%
- %% {ok, Pools} = application:get_env(hello_erlang, mongodb_pools),
- %% PoolSpecs = lists:map(fun({Name, SizeArgs, WorkerArgs}) ->
- %% PoolArgs = [{name, {local, Name}},
- %% {worker_module, db_mongo_handler}] ++ SizeArgs,
- %% poolboy:child_spec(Name, PoolArgs, WorkerArgs)
- %% end, Pools),
- %% {ok, {{one_for_one, 10, 10}, [PoolSpecs]}}.
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- hello_handler.erl
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- -module(hello_handler).
- -behaviour(cowboy_http_handler).
- -export([init/3]).
- -export([handle/2]).
- -export([terminate/3]).
- -define(DB_Conn_Pool, mg_pool1).
- init(_, Req, Opts) ->
- {ok, Req, Opts}.
- handle(Req, State) ->
- case cowboy_req:method(Req) of
- {<<"GET">>, Req2} ->
- {UserName, Req3} = cowboy_req:binding(user_name, Req2),
- io:format("***************************Debug*********************************~n Module:~p ~n Line:~p ~n UserName:~p ~n", [?MODULE, ?LINE, UserName]),
- get_user(UserName, Req3);
- {<<"DELETE">>, Req2} ->
- {UserName, Req3} = cowboy_req:binding(user_name, Req2),
- delete_user(UserName, Req3);
- {<<"POST">>, Req2} ->
- {ok, Body, Req3} = cowboy_req:body(Req2),
- UserInfo = jiffy:decode(Body),
- {[{<<"name">>, NameValue}, {<<"age">>, AgeValue}]} = UserInfo,
- io:format("--Body is ~p ~n --UserInfo is ~p ~n --NameValue is ~p ~n --AgeValue is ~p ~n", [Body, UserInfo, NameValue, AgeValue]),
- add_user(NameValue, AgeValue, Req3);
- {<<"PUT">>, Req2} ->
- {ok, Body, Req3} = cowboy_req:body(Req2),
- UserInfo = jiffy:decode(Body),
- {[{<<"name">>, NameValue}, {<<"age">>, AgeValue}]} = UserInfo,
- io:format("--Body is ~p ~n --UserInfo is ~p ~n --NameValue is ~p ~n --AgeValue is ~p ~n", [Body, UserInfo, NameValue, AgeValue]),
- update_user(NameValue, AgeValue, Req3)
- end.
- get_user(Name, Req) ->
- Collection = <<"user">>,
- Selector = {name, Name},
- Worker = poolboy:checkout(?DB_Conn_Pool),
- io:format("***************************Debug*********************************~n Module:~p ~n Line:~p ~n Worker:~p ~n", [?MODULE, ?LINE, Worker]),
- Request = {get_user, {Collection, Selector}},
- UserInfo = gen_server:call(Worker, Request),
- io:format("***************************Debug*********************************~n Module:~p ~n Line:~p ~n UserInfo:~p ~n", [?MODULE, ?LINE, UserInfo]),
- cowboy_req:reply(200, [
- {<<"content-type">>, <<"text/plain">>}
- ], UserInfo, Req).
- %% Add user
- add_user(Name, Age, Req) ->
- {Database, Collection} = {<<"user">>, <<"user">>},
- {ok, Connection} = mongo:connect("127.0.0.1", 27017, Database),
- mongo:insert(Connection, Collection, [{name, Name, age, Age}]).
- %%Update user
- update_user(Name, Age, Req) ->
- {Database, Collection} = {<<"user">>, <<"user">>},
- {ok, Connection} = mongo:connect("127.0.0.1", 27017, Database),
- Command = {'$set', {age, Age}},
- mongo:update(Connection, Collection, {name, Name}, Command).
- %%Delete user
- delete_user(Name, Req) ->
- {Database, Collection} = {<<"user">>, <<"user">>},
- {ok, Connection} = mongo:connect("127.0.0.1", 27017, Database),
- Selector = {name, Name},
- mongo:delete(Connection, Collection, Selector).
- terminate(_Reason, _Req, _State) ->
- ok.
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- start.erl
- %%%%%%%%%%%%%%%%
- %%%%%%%%%%%%%%%%
- -module(start).
- -author("zhouhuakang").
- %% API
- -export([]).
- -export([
- start_applications/1, stop_applications/1, server_start/0]).
- -define(SERVER_APPS, [sasl,ranch,crypto,cowlib,cowboy,bson,mongodb,jiffy,hello_erlang]).
- server_start()->
- try
- ok = start_applications(?SERVER_APPS)
- after
- timer:sleep(100)
- end.
- manage_applications(Iterate, Do, Undo, SkipError, ErrorTag, Apps) ->
- Iterate( fun (App, Acc) ->
- case Do(App) of
- ok -> [App | Acc];
- {error, {SkipError, _}} -> Acc;
- {error, Reason} ->
- lists:foreach(Undo, Acc),
- throw({error, {ErrorTag, App, Reason}})
- end
- end, [], Apps),
- ok.
- start_applications(Apps) ->
- manage_applications(fun lists:foldl/3,
- fun application:start/1,
- fun application:stop/1,
- already_started,
- cannot_start_application,
- Apps).
- stop_applications(Apps) ->
- manage_applications(fun lists:foldr/3,
- fun application:stop/1,
- fun application:start/1,
- not_started,
- cannot_stop_application,
- Apps).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement