Skip to content

Instantly share code, notes, and snippets.

@phillipoertel
Last active June 14, 2024 15:09
Show Gist options
  • Save phillipoertel/d5e4a60ff6dc5c7aaf8d1eadcd28b354 to your computer and use it in GitHub Desktop.
Save phillipoertel/d5e4a60ff6dc5c7aaf8d1eadcd28b354 to your computer and use it in GitHub Desktop.
redis counts
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'redis'
gem "hiredis-client"
# gem 'rspec'
end
require "hiredis-client" # speed optimized redis client
require 'date'
# CONSTANTS
NUM_VIEWS = 10
PROPERTY_IDS = [42, 43]
DAYS_TRACKED = 2
SECONDS_IN_A_DAY = 24 * 60 * 60
# METHODS
def cache_key(property_id, date)
"properties:views:#{property_id}:#{date}"
end
def set_key_expiry(redis, key, date)
expiry_date_timestamp = date + (DAYS_TRACKED * SECONDS_IN_A_DAY) + 1
redis.expireat(key, expiry_date_timestamp)
end
def track_property_view(redis, property_id, date)
# generate the cache key
key = cache_key(property_id, date)
# always increment
view_count = redis.incr(key)
# if view_count is 1, this is a new key. then also set expiry
set_key_expiry(redis, key, date) if view_count == 1
# puts "#{key}: #{view_count} views, expires at: #{Time.at(redis.expiretime(key))}"
end
def get_property_views(redis, property_id, date_keys)
keys = date_keys.map { |date| cache_key(property_id, date) }
redis.mget(*keys).sum(&:to_i)
end
# START CODE
redis = Redis.new
redis.flushall
# generate an array of unix timestamps for the last DAYS_TRACKED days
date_keys = ((Date.today - DAYS_TRACKED + 1)..Date.today).map { |date| date.to_time.utc.to_i }
# generate some fake property views (sample data)
NUM_VIEWS.times do |i|
property_id = PROPERTY_IDS.sample
date = date_keys.sample
track_property_view(redis, property_id, date)
end
# show views
PROPERTY_IDS.each do |property_id|
views_count = get_property_views(redis, property_id, date_keys)
puts "Property #{property_id}: #{views_count} views in the last #{DAYS_TRACKED} days"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment