Reputation: 38812
I see that Redis doesn't allow make an increment
and an expiration
at the same time. I solved this doing it in 2 steps:
my_redis_client.incrby( key, amount )
my_redis_client.expire( key, expire_time )
But if I want to use Rails.cache
I don't know how to obtain the same result in the most optimal way.
If I do this:
Rails.cache.increment( key, amount, :expires_in => expire_time )
The expires_in
is completely ignored.
Is there any way to set an expiration time and execute an increment using Rails.cache
?
Upvotes: 3
Views: 2816
Reputation: 38812
This is what worked for me in Rails 5.2
Rails.cache.write(key, 0, :raw => true, :unless_exist => true, :expires_in => expire_time)
Rails.cache.increment( key, amount )
Upvotes: 2
Reputation: 38812
Looks like in Rails 6.0.0 the:
Rails.cache.increment( key, amount, :expires_in => expire_time )
works as expected:
Upvotes: 3
Reputation: 2478
One option is to monkeypatch Rails.cache
ie
module CacheSupport
def increment_with_ttl(key, amount, ttl)
increment(key, amount)
expire(key, ttl)
end
end
Rails.cache.extend(CacheSupport)
Put this in initializer
folder then you can start using Rails.cache.increment_with_ttl()
in your project
Upvotes: 1