Created
May 9, 2012 15:06
-
-
Save critzjm/2645248 to your computer and use it in GitHub Desktop.
Redis Counters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module RedisCounter | |
# increment counters | |
def self.incr(name, uniq_key=nil) | |
time = Time.now | |
REDIS.multi do |r| | |
key_names.each do |key_name| | |
# count | |
incr_key = send("#{key_name}_key", name, time) | |
REDIS.incr(incr_key) | |
# uniq count | |
if uniq_key | |
set_key = send("#{key_name}_key", "#{name}:uniq", time) | |
REDIS.sadd(set_key, uniq_key) | |
end | |
end | |
end | |
end | |
# return counts for the given time | |
def self.counts(name, time=Time.now) | |
{ | |
:total => get_counts(name, "total", time), | |
:year => get_counts(name, "year", time), | |
:month => get_counts(name, "month", time), | |
:day => get_counts(name, "day", time), | |
:hour => get_counts(name, "hour", time), | |
:min => get_counts(name, "min", time), | |
:sec => get_counts(name, "sec", time) | |
} | |
end | |
private | |
def self.get_counts(name, precision, time) | |
count = count(name, precision, time) | |
uniq = count_uniq(name, precision, time) | |
avg = uniq > 0 ? (count/uniq) : 0 | |
{ | |
:count => count, | |
:uniq => uniq, | |
:avg => avg | |
} | |
end | |
def self.count(name, precision, time) | |
key = send("#{precision}_key", name, time) | |
REDIS.get(key).to_i | |
end | |
def self.count_uniq(name, precision, time) | |
key = send("#{precision}_key", "#{name}:uniq", time) | |
REDIS.scard(key).to_i | |
end | |
def self.key_names | |
[ | |
"total", | |
"year", | |
"month", | |
"day", | |
"hour", | |
"min", | |
"sec" | |
] | |
end | |
def self.total_key(name, time) | |
["peelr", name].join(":") | |
end | |
def self.year_key(name, time) | |
[total_key(name, time), time.year].join(":") | |
end | |
def self.month_key(name, time) | |
[year_key(name, time), time.month].join(":") | |
end | |
def self.day_key(name, time) | |
[month_key(name, time), time.day].join(":") | |
end | |
def self.hour_key(name, time) | |
[day_key(name, time), time.hour].join(":") | |
end | |
def self.min_key(name, time) | |
[hour_key(name, time), time.min].join(":") | |
end | |
def self.sec_key(name, time) | |
[min_key(name, time), time.sec].join(":") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment