-
-
Save scan/2654564 to your computer and use it in GitHub Desktop.
Code to accompany the blog post http://www.lukemelia.com/blog/archives/2010/01/17/redis-in-practice-whos-online/
This file contains hidden or 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
require 'redis' | |
# SADD key, member | |
# Adds the specified <i>member</i> to the set stored at <i>key</i>. | |
redis = Redis.new | |
redis.sadd 'my_set', 'foo' # => true | |
redis.sadd 'my_set', 'bar' # => true | |
redis.sadd 'my_set', 'bar' # => false | |
redis.smembers 'my_set' # => ["foo", "bar"] | |
# SUNION key1 key2 ... keyN | |
# Returns the members of a set resulting from the union of all the sets stored at the specified keys. | |
# SUNIONSTORE <i>dstkey key1 key2 ... keyN</i></b> | |
# Works like SUNION but instead of being returned the resulting set is stored as dstkey. | |
redis = Redis.new | |
redis.sadd 'set_a', 'foo' | |
redis.sadd 'set_a', 'bar' | |
redis.sadd 'set_b', 'bar' | |
redis.sadd 'set_b', 'baz' | |
redis.sunion 'set_a', 'set_b' # => ["foo", "baz", "bar"] | |
redis.sunionstore 'set_ab', 'set_a', 'set_b' | |
redis.smembers 'set_ab' # => ["foo", "baz", "bar"] | |
# SINTER key1 key2 ... keyN | |
# Returns the members that are present in all sets stored at the specified keys. | |
redis = Redis.new | |
redis.sadd 'set_a', 'foo' | |
redis.sadd 'set_a', 'bar' | |
redis.sadd 'set_b', 'bar' | |
redis.sadd 'set_b', 'baz' | |
redis.sinter 'set_a', 'set_b' # => ["bar"] |
This file contains hidden or 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
# Defining the keys | |
def current_key | |
key(Time.now.strftime("%M")) | |
end | |
def keys_in_last_5_minutes | |
now = Time.now | |
times = (0..5).collect {|n| now - n.minutes } | |
times.collect{ |t| key(t.strftime("%M")) } | |
end | |
def key(minute) | |
"online_users_minute_#{minute}" | |
end | |
# Tracking an Active User | |
def track_user_id(id) | |
key = current_key | |
redis.sadd(key, id) | |
end | |
# Who's online | |
def online_user_ids | |
redis.sunion(*keys_in_last_5_minutes) | |
end | |
def online_friend_ids(interested_user_id) | |
redis.sunionstore("online_users", *keys_in_last_5_minutes) | |
redis.sinter("online_users", "user:#{interested_user_id}:friend_ids") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment