Class: Barrage::Generators::RedisWorkerId

Inherits:
Base
  • Object
show all
Defined in:
lib/barrage/generators/redis_worker_id.rb

Defined Under Namespace

Classes: Finalizer

Constant Summary collapse

RACE_CONDITION_TTL =
30

Instance Attribute Summary

Attributes inherited from Base

#options

Instance Method Summary collapse

Methods inherited from Base

#length

Constructor Details

#initialize(options = {}) ⇒ RedisWorkerId

Returns a new instance of RedisWorkerId.



10
11
12
13
14
15
16
17
18
# File 'lib/barrage/generators/redis_worker_id.rb', line 10

def initialize(options = {})
  @worker_id = nil
  @worker_ttl = 0
  @real_ttl   = 0
  super
  @data = []
  @finalizer_proc = Finalizer.new(@data)
  ObjectSpace.define_finalizer(self, @finalizer_proc)
end

Instance Method Details

#generateObject Also known as: current



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/barrage/generators/redis_worker_id.rb', line 20

def generate
  now = Time.now.to_i
  if @worker_ttl - now <= 0
    @data[1] = @worker_id = renew_worker_id
    # check redis after half of real ttl
    @worker_ttl = now + ttl / 2
    @real_ttl   = now + ttl
    @data[2] = @real_ttl
  end
  @worker_id
end

#redisObject



37
38
39
# File 'lib/barrage/generators/redis_worker_id.rb', line 37

def redis
  @redis ||= @data[0] = Redis.new(options["redis"] || {})
end

#ttlObject



33
34
35
# File 'lib/barrage/generators/redis_worker_id.rb', line 33

def ttl
  options["ttl"]
end