basic key get/put
This commit is contained in:
parent
281938a05d
commit
155c24a535
1 changed files with 28 additions and 16 deletions
|
@ -4,7 +4,8 @@
|
|||
|
||||
-export([
|
||||
start_link/0,
|
||||
get_vnode/1
|
||||
get_local/2,
|
||||
put_local/3
|
||||
]).
|
||||
|
||||
%%% gen_server callbacks
|
||||
|
@ -19,8 +20,13 @@
|
|||
start_link() ->
|
||||
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
|
||||
|
||||
get_vnode(Index) ->
|
||||
gen_server:call(?MODULE, {get_vnode, Index}).
|
||||
-spec get_local(Index :: non_neg_integer(), Key :: term()) -> {ok, Value :: term()} | none.
|
||||
get_local(Index, Key) ->
|
||||
gen_server:call(?MODULE, {get, Index, Key}).
|
||||
|
||||
-spec put_local(Index :: non_neg_integer(), Key :: term(), Value :: term()) -> ok.
|
||||
put_local(Index, Key, Value) ->
|
||||
gen_server:cast(?MODULE, {put, Index, Key, Value}).
|
||||
|
||||
%%% gen_server callbacks
|
||||
|
||||
|
@ -28,17 +34,23 @@ get_vnode(Index) ->
|
|||
init([]) ->
|
||||
{ok, #kv_vnode_manager{table = ets:new(?MODULE, [set])}}.
|
||||
|
||||
handle_call({get_vnode, Index}, _From, State) ->
|
||||
Table = State#kv_vnode_manager.table,
|
||||
Reply =
|
||||
case ets:lookup(Table, Index) of
|
||||
[{_, Pid}] ->
|
||||
{ok, Pid};
|
||||
[] ->
|
||||
{ok, Pid} = kv_vnode_sup:start_vnode(Index),
|
||||
ets:insert(Table, {Index, Pid}),
|
||||
{ok, Pid}
|
||||
end,
|
||||
{reply, Reply, State}.
|
||||
handle_call({get, Index, Key}, _From, State) ->
|
||||
VNode = get_vnode(Index, State),
|
||||
{reply, kv_vnode:get(VNode, Key), State}.
|
||||
|
||||
handle_cast(_, _) -> error(not_implemented).
|
||||
handle_cast({put, Index, Key, Value}, State) ->
|
||||
VNode = get_vnode(Index, State),
|
||||
ok = kv_vnode:put(VNode, Key, Value),
|
||||
{noreply, State}.
|
||||
|
||||
%%% internal functions
|
||||
|
||||
get_vnode(Index, #kv_vnode_manager{table = Table}) ->
|
||||
case ets:lookup(Table, Index) of
|
||||
[{_, Pid}] ->
|
||||
Pid;
|
||||
[] ->
|
||||
{ok, Pid} = kv_vnode_sup:start_vnode(Index),
|
||||
ets:insert(Table, {Index, Pid}),
|
||||
Pid
|
||||
end.
|
||||
|
|
Loading…
Add table
Reference in a new issue