Class: Counters::Redis

Inherits:
Base
  • Object
show all
Defined in:
lib/counters/redis.rb

Constant Summary collapse

SCALING_FACTOR =

Redis requires integer keys, thus we scale all latencies to the nanosecond precision

1_000_000_000

Instance Attribute Summary

Attributes inherited from Base

#namespace

Instance Method Summary collapse

Methods inherited from Base

#hit, #latency, #magnitude, #ping

Constructor Details

#initialize(redis = Redis.new, options = {}) ⇒ Redis

Returns a new instance of Redis.



6
7
8
9
10
11
# File 'lib/counters/redis.rb', line 6

def initialize(redis=Redis.new, options={})
  super(options)

  @redis    = redis
  @base_key = options.fetch(:base_key) { raise "Missing :base_key from #{options.inspect}" }
end

Instance Method Details

#record_hit(key) ⇒ Object



13
14
15
# File 'lib/counters/redis.rb', line 13

def record_hit(key)
  @redis.hincrby(@base_key, "hits.#{key}", 1)
end

#record_latency(key, latency_in_seconds) ⇒ Object



31
32
33
34
# File 'lib/counters/redis.rb', line 31

def record_latency(key, latency_in_seconds)
  @redis.hincrby(@base_key, "latencies.#{key}.count", 1)
  @redis.hincrby(@base_key, "latencies.#{key}.nanoseconds", (latency_in_seconds * SCALING_FACTOR).to_i)
end

#record_magnitude(key, amount) ⇒ Object



17
18
19
20
21
22
# File 'lib/counters/redis.rb', line 17

def record_magnitude(key, amount)
  @redis.multi do
    @redis.hincrby(@base_key, "magnitudes.#{key}.value", amount)
    @redis.hincrby(@base_key, "magnitudes.#{key}.count", 1)
  end
end

#record_ping(key) ⇒ Object



24
25
26
# File 'lib/counters/redis.rb', line 24

def record_ping(key)
  @redis.hset(@base_key, "pings.#{key}", Time.now.utc.to_i)
end