elang 游戏 生成全局id

来源:互联网 发布:广州恒大淘宝队官网 编辑:程序博客网 时间:2024/05/13 16:00

一:全局Id是什么

游戏内的玩家/物品/坐骑等世界唯一id

二:为什么不用数据库自增id

数据库自增id可定制性比较差

当合服时,无论1服,2服 在数据库中玩家id都是 1-xxxxx 递增, 合服时如何处理这部分是个大问题

所以我们选择自己生成id,1服生成出来的id为 10000000xxxx 2服为 20000000xxxxx,这样合服就可以直接合数据

三:生成方式

ets 有一个函数是 update_counter 

解释如下,

update_counter(Tab, Key, UpdateOp) -> Resultupdate_counter(Tab, Key, UpdateOp :: [UpdateOp]) -> [Result]update_counter(Tab, Key, Incr) -> ResultTypes:Tab = tab()Key = term()UpdateOp = {Pos, Incr} | {Pos, Incr, Threshold, SetValue}Pos = Incr = Threshold = SetValue = Result = integer()This function provides an efficient way to update one or more counters, without the hassle of having to look up an object, update the object by incrementing an element and insert the resulting object into the table again. 
我一看,简直就是为生成全局id而生啊

赶紧用上

get_global_player_id(ServerId) ->

    ets:update_counter(ets_global_counter, {player_id, ServerId}, 1).

通过服id获取到玩家id

后来有一位同事提出 update_counter性能有问题,不如建立一个gen_server 用进程字典维护这个全局id

so ..是这样么

自己做了一个简单的测试,代码就不贴了,比较简单,就是每种生成方式调用100万次比较时间

最后得到的比例大概为

使用进程 字典用时 4.3秒,ets用时4.75秒,同时数据大概加到1000万左右,并没有发现随着数字加大update_counter效率降低

进程字典效率确实比update_counter要高一下,但是update_counter也没有到不能忍受的地步

同时,由于使用进程字典担心进程挂掉数据丢失,所以最后决定沿用update_counter 将ets由一个公用进程挂载起来

0 0