Skip to content

Instantly share code, notes, and snippets.

@printercu
Created November 13, 2018 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save printercu/275b28d97f460bfb3406b0ca48121882 to your computer and use it in GitHub Desktop.
Save printercu/275b28d97f460bfb3406b0ca48121882 to your computer and use it in GitHub Desktop.
class RedisStats
attr_reader :redis, :pattern
def initialize(redis, pattern = '*')
@redis = redis
@pattern = pattern
end
def all_keys
@all_keys ||= [].tap do |result|
cursor = 0
loop do
cursor, keys = redis.scan(cursor, match: pattern)
result.concat(keys)
break if cursor == '0'
end
end
end
def debugs
@debugs ||= debug_for(all_keys)
end
def debug_for(keys)
keys.map do |key|
debug = redis.debug(:object, key) rescue nil
debug&.split(/:| /)&.drop(1)&.each_slice(2)&.to_h
end.compact
end
def total_size
@total_size ||= debugs.sum { |x| x['serializedlength'].to_i }
end
def avg_size
total_size / debugs.size
end
def total_extrapolated_size
all_keys.size * avg_size
end
def summary
{
keys_fetched: all_keys.size,
keys_debugged: debugs.size,
total_size: "#{(total_size.to_f / 1.gigabyte).round(2)} GB",
avg_size: "#{(avg_size.to_f / 1.megabyte).round(2)} MB",
total_extrapolated_size: "#{(total_extrapolated_size.to_f / 1.gigabyte).round(2)} GB",
}
end
end
# stats = RedisStats.new(Rails.cache.data, 'rails42:marketplace_offers:*')
# stats.summary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment