Last active
October 14, 2017 04:03
-
-
Save oshinko/ba350aa7786c2c5cf89a7d4a4466a908 to your computer and use it in GitHub Desktop.
Redis Snowflake for Python.
This file contains 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
import redis | |
import time | |
def snowflake(redis, epoch=0): | |
return redis.register_script(f""" | |
local node = tonumber(redis.call('HGET', 'globals', 'node')) % 1024 | |
local seq = tonumber(redis.call('HINCRBY', 'globals', 'sequence', 1)) % 4096 | |
local time = redis.call('TIME') | |
local time41 = ((tonumber(time[1]) * 1000) + (tonumber(time[2]) / 1000)) - {epoch} | |
return (time41 * (2 ^ 22)) + (node * (2 ^ 12)) + seq | |
""")() | |
ds = redis.StrictRedis(host='localhost', port=6379, db=0) | |
ds.hset('globals', 'node', 0) | |
epoch = 1507952997821 # service started | |
for n in range(8): | |
print(snowflake(ds, epoch)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment