menuTicketing

Ticketing Ruby 라이브러리

GitHub

리포지토리

예제

간단한 예제

서버에 연결해 락을 하나 획득한 뒤 곧바로 반납하는 가장 단순한 흐름입니다.

ruby
broker = Broker.connect(addr)
begin
  broker.wait_ready(5)

  ticket = broker.acquire("key", wait: 5, lease: 30)
  ticket.release

  puts "pass"
ensure
  broker.close
end

동시성 예제 (분산 락)

여러 스레드가 동시에 계좌별 락으로 보호받으며 입출금을 반복해도, 모든 계좌 잔액이 결국 시작값으로 돌아오는지 확인하는 예제입니다.

ruby
def transaction(broker, balances, account, delta, log)
  key = "account-#{account}"
  ticket =
    begin
      broker.acquire(key, wait: WAIT, lease: LEASE)
    rescue StandardError => e
      log.error("account #{account} acquire failed: #{e}")
      return
    end

  before = balances[account]
  Thread.pass
  after = before + delta
  balances[account] = after
  ticket.release

  action, sign = delta < 0 ? ["withdraw", "-"] : ["deposit", "+"]
  log.info("account #{account} #{action} #{sign}$#{AMOUNT} -> $#{after}")
end

전체 예제는 test_example.rb, test_bank_example.rb, test_bench.rb에서 확인하세요.