Created
October 30, 2012 08:40
-
-
Save lhwork/3979039 to your computer and use it in GitHub Desktop.
erlang crc32 hash 算法 使用 put get
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(erichash). | |
-export([start/2, getTargetInfo/1]). | |
-define(HOST_LIST_ETS_NAME , hostlist). | |
-define(PROCESS_LIST_NAME , pl). | |
start(HostList , Num) when is_list(HostList), is_integer(Num) -> | |
erase(?PROCESS_LIST_NAME), | |
targets(HostList, Num), | |
self(). | |
targets(HostList , Renum) when is_list(HostList) -> | |
CrcList = lists:map(fun({Key, Info}) -> | |
NewList = createKey(Renum, Key, []), | |
[{erlang:crc32(NewKey), Key, Info} || NewKey <- NewList] | |
end, | |
HostList), | |
setHostCache_processlist(lists:ukeysort(1, lists:merge(CrcList))). | |
% | |
% use process list saving HostList | |
% putkey,Info get(key) | |
% | |
setHostCache_processlist(HostList) when is_list(HostList) -> | |
case get(?PROCESS_LIST_NAME) of | |
undefined -> | |
put(?PROCESS_LIST_NAME, HostList); | |
Info -> | |
Info | |
end. | |
% | |
% use ets saving HostList | |
% | |
%setHostCache_ets(HostList) when is_list(HostList) -> | |
% CacheId = ets:new(?HOST_LIST_ETS_NAME, [ordered_set,public,named_table]), | |
% [ets:insert(CacheId, Info) || Info <- HostList], | |
% ets:tab2list(?HOST_LIST_ETS_NAME). | |
getTargetInfo(UserKey) when is_list(UserKey) -> | |
%using ets for geting HostList | |
%HostList = ets:tab2list(?HOST_LIST_ETS_NAME), | |
%using process list for geting HostList | |
HostList = get(?PROCESS_LIST_NAME), | |
try getHostInfo(HostList, UserKey) of | |
NewList -> | |
if | |
length(NewList) >= 1 -> | |
[H|_] = NewList, | |
{ok, H}; | |
true -> | |
[H|_] = HostList, | |
{ok, H} | |
end | |
catch | |
_:_ -> | |
[H|_] = HostList, | |
{ok, H} | |
end. | |
getHostInfo(HostList, UserKey) -> | |
[{Num, Key, Info} || {Num , Key , Info} <- HostList , Num >= erlang:crc32(UserKey) ]. | |
createKey(0, Key, NewList) when is_list(Key), is_list(NewList) -> | |
NewList++[Key++"0"]; | |
createKey(Num, Key, NewList) when is_list(Key), is_list(NewList), is_integer(Num) -> | |
NumTem = erlang:abs(Num), | |
createKey(NumTem-1, Key, NewList++[Key++integer_to_list(NumTem)]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment