Use Redis to generate unique ID from a limited range

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 04:14:54

How about using Bitmaps to record, for every possible nbr, whether or not that value is used?

To record that a value is taken use SETBIT:

SETBIT key [nbr] 1

To find a free nbr use BITPOS:

BITPOS key 0

To avoid race conditions you'll want to make sure your get-and-set is atomic. [The OP addresses this in a follow-up question.]

This will require very little memory (8K bytes for 65536 possible values). BITPOS is O(n), but that's unlikely to be a real problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!