Skip to content

Instantly share code, notes, and snippets.

@taka-wang
Last active March 23, 2024 13:13
Show Gist options
  • Save taka-wang/768929c518fbee637a2094b565a912db to your computer and use it in GitHub Desktop.
Save taka-wang/768929c518fbee637a2094b565a912db to your computer and use it in GitHub Desktop.
確保enqueue的atomic
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
lua_script = """
local queue_length = redis.call('llen', KEYS[1])
if queue_length > 0 then
-- get the last number
local last_number = redis.call('lindex', KEYS[1], -1)
local new_number = tonumber(last_number) + 1
-- add new number to the queue
redis.call('rpush', KEYS[1], new_number)
-- return the new number and the queue length
return {new_number, queue_length}
else
-- handle empty queue exception
return {nil, 0}
end
"""
queue_name = f'waiting:store:{3}:capacity:{2}'
result = r.eval(lua_script, 1, queue_name)
new_number, queue_length = result[0], result[1]
if new_number:
print(f"下一個號碼是: {new_number}, 當前等待桌數: {queue_length}")
else:
# handle_empty_queue_exception()
class Singleton:
_instance = None # 底線表示 private
@classmethod
def get_instance(cls):
if not cls._instance:
# 如果不存在,則創建一個新的instance
cls._instance = cls()
return cls._instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment