asyncio 기반 API입니다. 서버 하나에 접속해 키를 획득하고 바로 반납합니다.
broker = TicketBroker.connect("127.0.0.1:5225")
try:
await broker.wait_ready(5)
ticket = await broker.acquire("key", wait=5, lease=30)
await ticket.release()
print("pass")
finally:
broker.close()여러 asyncio 태스크가 계좌별 락으로 상호배제하며 입금/출금을 반복해도 잔액이 항상 시작값으로 돌아오는지 검증하는 예제입니다. async with ticket을 쓰면 블록을 빠져나갈 때 자동으로 반납됩니다.
async def transaction(broker: TicketBroker, account: int, delta: int) -> None:
key = f"account-{account}"
try:
ticket = await broker.acquire(key, WAIT, LEASE)
except Exception as e:
log.error("account %s acquire failed: %s", account, e)
return
async with ticket:
before = BALANCES[account]
await asyncio.sleep(0)
after = before + delta
BALANCES[account] = after
action, sign = ("withdraw", "-") if delta < 0 else ("deposit", "+")
log.info("account %s %s %s$%s -> $%s", account, action, sign, AMOUNT, after)전체 예제는 test_example.py, test_bank.py, test_bench.py에서 확인하세요.