resque/redis-namespace

Calling redis name space for every /show controller

Closed this issue · 2 comments

I want to use redis name space to create a key/value pair of users currently watching a video from videos/:id/show. I'd like the name space to be the I'd of the video, the key to be the user ID and the value to be the timestamp of visit with an expiration.

Should I call redis::namespace.new(ns => videoid) every time I call the controller? I already define redis in my redis.rb file.

You can totally create a new redis-namespace wrapper around your redis connection for every time you call the controller, but there are also other options:

First, you could just compose the key yourself when setting the value; this is functionally what the redis-namespace gem does behind the scenes:

# assuming:
#   `video_id` is a String
#   `user_id` is a String
#   `ttl` is a Fixnum
redis.setex("video:#{video_id}:user:#{user_id}", ttl, Time.now.to_i)

Alternatively, you could memoize your Redis::Namespace wrappers, reusing each wrapper for all the video views for a particular video (which could be a good idea, but only if you have a smallish number of videos, since these each take up a little bit of memory and will never be garbage collected):

# in an initializer somewhere
redis_video_namespaces = Hash.new { |hash, video_id| hash[video_id] = Redis::Namespace.new("video:#{video_id}", redis: redis)

# then in your code when incrementing, assuming:
#   `video_id` is a String
#   `user_id` is a String
#   `ttl` is a Fixnum
redis_video_namespaces[video_id].setex("user:#{user_id}", ttl, Time.now.to_i)

This is great! I just create the namespace wrapper as needed whenever the controller gets pinged. It makes more sense than to keep the namespaces in memory from an initializer - since I expect the namespace to be garbage collected since it was created in the controller.

Thanks for the help - it helped me understand how namespace works and made my code incredibly more efficient.