redis cache populates

This commit is contained in:
Ilya Zhitomirskiy 2011-09-30 11:09:30 -07:00
parent 01515725fe
commit 289d582ce9
2 changed files with 8 additions and 20 deletions

View file

@ -11,7 +11,6 @@ class RedisCache
def initialize(user, order_field)
@user = user
@order_field = order_field.to_s
self
end
# @return [Boolean]
@ -29,19 +28,14 @@ class RedisCache
post_ids[0...limit]
end
# @return [RedisCache] self
def ensure_populated!
self.repopulate! unless cache_exists?
self
end
# @return [RedisCache] self
def repopulate!
self.populate! && self.trim!
self
end
# @return [RedisCache] self
def populate!
# user executes query and gets back hashes
sql = @user.visible_posts_sql(:limit => CACHE_LIMIT, :order => self.order)
@ -50,19 +44,13 @@ class RedisCache
# hashes are inserted into set in a single transaction
redis.multi do
hashes.each do |h|
self.redis.zadd(set_key, h[@order_field], h["id"])
self.redis.zadd(set_key, h[@order_field].to_i, h["id"])
end
end
self
end
# @return [RedisCache] self
def trim!
puts "cache limit #{CACHE_LIMIT}"
puts "cache size #{self.size}"
self.redis.zremrangebyrank(set_key, 0, -(CACHE_LIMIT+1))
self
end
# @param order [Symbol, String]

View file

@ -40,21 +40,21 @@ describe RedisCache do
@timestamp = Time.now.to_i
30.times do |n|
created_time = @timestamp - n*1000
@redis.zadd("cache_stream_#{bob.id}_created_at", created_time, n)
@redis.zadd("cache_stream_#{bob.id}_created_at", created_time, n.to_s)
@timestamps << created_time
end
end
it 'returns the most recent post ids (default created at, limit 15)' do
@cache.post_ids.should =~ 15.times.map {|n| n}
@cache.post_ids.should =~ 15.times.map {|n| n.to_s}
end
it 'returns posts ids after the specified time' do
@cache.post_ids(@timestamps[15]).should =~ (15...30).map {|n| n}
@cache.post_ids(@timestamps[15]).should =~ (15...30).map {|n| n.to_s}
end
it 'returns post ids with a non-default limit' do
@cache.post_ids(@timestamp, 20).should =~ 20.times.map {|n| n}
@cache.post_ids(@timestamp, 20).should =~ 20.times.map {|n| n.to_s}
end
end
@ -112,7 +112,7 @@ describe RedisCache do
@timestamp = Time.now.to_i
30.times do |n|
created_time = @timestamp - n*1000
@redis.zadd("cache_stream_#{bob.id}_created_at", created_time, n)
@redis.zadd("cache_stream_#{bob.id}_created_at", created_time, n.to_s)
@timestamps << created_time
end
@ -126,11 +126,11 @@ describe RedisCache do
@timestamp = Time.now.to_i
120.times do |n|
created_time = @timestamp - n*1000
@redis.zadd("cache_stream_#{bob.id}_created_at", created_time, n)
@redis.zadd("cache_stream_#{bob.id}_created_at", created_time, n.to_s)
@timestamps << created_time
end
post_ids = 100.times.map{|n| n}
post_ids = 100.times.map{|n| n.to_s}
@cache.trim!
@cache.post_ids(Time.now.to_i, @cache.size).should == post_ids[0...100]
end