%%%------------------------------------------------------------------- %%% @author aresei %%% @copyright (C) 2017, %%% @doc %%% %%% @end %%% Created : 21. 四月 2017 13:33 %%%------------------------------------------------------------------- -module(redis_client). -author("aresei"). %% API -export([hget/2, hgetall/1]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HashTable处理 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec hget(Key :: binary(), Field :: binary()) -> {ok, Val :: any()} | {error, Reason :: binary()}. hget(Key, Field) when is_binary(Key), is_binary(Field) -> poolboy:transaction(redis_pool, fun(Conn) -> eredis:q(Conn, ["HGET", Key, Field]) end). -spec hgetall(Key :: binary()) -> {ok, Fields :: map()} | {error, Reason :: binary()}. hgetall(Key) when is_binary(Key) -> poolboy:transaction(redis_pool, fun(Conn) -> case eredis:q(Conn, ["HGETALL", Key]) of {ok, Items} -> {ok, to_map(Items)}; Error -> Error end end). to_map(Items) when is_list(Items), length(Items) rem 2 == 0 -> to_map(Items, #{}). to_map([], Target) -> Target; to_map([K, V|Tail], Target) -> to_map(Tail, Target#{K => V}).