本节将演示如何在riak client集成进mochiweb应用中。
riak-erlang-client : https://github.com/basho/riak-erlang-client
首先请参阅http://blog.csdn.net/kunshan_shenbin/article/details/7578600,了解如何创建并运行mochiweb应用。
修改rebar.config修改如下:
%% -*- erlang -*-
{erl_opts, [debug_info]}.
{deps, [
{mochiweb, ".*", {git, "git://github.com/mochi/mochiweb.git", "master"}},
{'riakc', ".*", {git, "git://github.com/basho/riak-erlang-client.git","master"}}
]
}.
{cover_enabled, true}.
{eunit_opts, [verbose, {report,{eunit_surefire,[{dir,"."}]}}]}.
然后
>make
>./start-dev.sh
启动程序。
另外,修改src/dyco_web.erl文件以适应自己的需求,示例如下:
%% @author Mochi Media <dev@mochimedia.com>
%% @copyright 2010 Mochi Media <dev@mochimedia.com>
%% @doc Web server for dyco.
-module(dyco_web).
-author("Mochi Media <dev@mochimedia.com>").
-export([start/1, stop/0, loop/2]).
%% External API
start(Options) ->
{DocRoot, Options1} = get_option(docroot, Options),
Loop = fun (Req) ->
?MODULE:loop(Req, DocRoot)
end,
mochiweb_http:start([{name, ?MODULE}, {loop, Loop} | Options1]).
stop() ->
mochiweb_http:stop(?MODULE).
loop(Req, DocRoot) ->
"/" ++ Path = Req:get(path),
try
case Req:get(method) of
Method when Method =:= 'GET'; Method =:= 'HEAD' ->
case Path of
"riak" ->
QueryStringData = Req:parse_qs(),
Id = proplists:get_value("id", QueryStringData, "0"),
Req:respond({200, [{"Content-Type", "application/json"}], "var json = " ++ get_data(Id)});
_ ->
Req:serve_file(Path, DocRoot)
end;
'POST' ->
case Path of
_ ->
Req:not_found()
end;
_ ->
Req:respond({501, [], []})
end
catch
Type:What ->
Report = ["web request failed",
{path, Path},
{type, Type}, {what, What},
{trace, erlang:get_stacktrace()}],
error_logger:error_report(Report),
%% NOTE: mustache templates need \ because they are not awesome.
Req:respond({500, [{"Content-Type", "text/plain"}], "request failed, sorry\n"})
end.
%% Internal API
get_option(Option, Options) ->
{proplists:get_value(Option, Options), proplists:delete(Option, Options)}.
%%
%% Tests
%%
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
you_should_write_a_test() ->
?assertEqual(
"No, but I will!",
"Have you written any tests?"),
ok.
-endif.
%%
%% Local Functions
%%
get_riak_pid() ->
{ok, Pid} = riakc_pb_socket:start_link("127.0.0.1", 8087), Pid.
get_data(Id) ->
Pid = get_riak_pid(),
{ok, O} = riakc_pb_socket:get(Pid, <<"Sample_Bucket">>, Id),
Value = riakc_obj:get_value(O),
riakc_pb_socket:stop(Pid),
Value.
然后通过如下URL访问: http://localhost:8080/riak?id=78