-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherdis_server.erl
96 lines (81 loc) · 2.44 KB
/
erdis_server.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
-module(erdis_server).
-export([start_server/0, stop_server/0]).
-record(entry, {key, value}).
initialize_db() ->
%create db, start mnesia
mnesia:create_schema([node()]),
mnesia:start(),
mnesia:create_table(entry, [{attributes, record_info(fields, entry)}]).
start_server() ->
initialize_db(),
{ok, Listen} = gen_tcp:listen(10101, [binary, {packet, 4}, {reuseaddr, true}, {active, true}]),
spawn(fun() -> par_connect(Listen) end).
par_connect(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
spawn(fun() -> par_connect(Listen) end),
loop(Socket).
stop_server() ->
mnesia:stop().
loop(Socket) ->
receive
{tcp, Socket, Bin} ->
io:format("Server received binary = ~p\n", [Bin]),
Str = binary_to_term(Bin),
Reply = process_command(Str),
BinReply = term_to_binary(Reply),
io:format("Server replying = ~s\n", [BinReply]),
gen_tcp:send(Socket, BinReply),
loop(Socket);
{tcp_closed, Socket} -> io:format("Server socket closed\n")
end.
process_command(Str) ->
Parts = string:split(Str, " ", all),
Command = lists:nth(1, Parts),
case Command of
"get" -> get_value(lists:nth(2, Parts));
"set" -> set_value(lists:nth(2, Parts), lists:nth(3, Parts));
"size" -> get_size();
"keys" -> get_all_keys();
"delete" -> delete(lists:nth(2, Parts));
"exists" -> exists(lists:nth(2, Parts))
end.
get_value(Key) ->
F = fun() ->
Oid = {entry, Key},
Entries = mnesia:read(Oid),
case Entries =:= [] of
true -> does_not_exists;
false -> lists:nth(1, Entries)
end
end,
mnesia:transaction(F).
set_value(Key, Value) ->
Entry = #entry{key = Key, value = Value},
F = fun() ->
mnesia:write(Entry)
end,
mnesia:transaction(F),
{ok, Key, Value}.
get_size() ->
F = fun() ->
mnesia:table_info(entry, size)
end,
{ok, mnesia:transaction(F)}.
get_all_keys() ->
F = fun() ->
mnesia:all_keys(entry)
end,
{ok, mnesia:transaction(F)}.
delete(Key) ->
Oid = {entry, Key},
F = fun() ->
mnesia:delete(Oid)
end,
mnesia:transaction(F),
{ok, Key}.
exists(Key) ->
Exists = get_value(Key),
case Exists of
{atomic, does_not_exists} -> false;
{atomic, _} -> true
end.