Rails caching, continue saving expired value

I have a long database query in one of our dashboard systems that I would like to cache, since the results do not have to be accurate in real time, but they can give a value "close enough" from the cache.

I would like to do this without having to wait for the user. I was looking at using something like

Rails.cache.write('my_val', 'val', :expires_in => 60.minutes) 

to keep this value, but I do not believe that it gives the exact functionality that I want. I would like to call using

  Rails.fetch('my_val') { create a background task to update my_val; return expired my_val} 

It seems that my_val is being removed from the cache when it expired. Is there a way to access this expired value, or perhaps another inline mechanism that would enable this functionality?

Thanks.

+4
source share
2 answers

Just do the following:

 Rails.cache.write('my_val', 'val') 

never expires

Now run the background job:

 SomeLongJob.process 

In the SomeLongJob.process job, do the following:

 def SomeLongJob.process some_long_calculation = Blah.calc Rails.cache.write('my_val', some_long_calculation) end 

Now read the data with

 def get_value val = Rails.cache.read('my_val', 'val') end 
+2
source

The parameter :race_condition_ttl for Rails.cache.fetch REALLY close to what you are looking for: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch

But from what I can say, the first request is still blocked (these are just subsequent ones that get the old value when it is updated). Not sure why they didn't go all the way. It would be better if the @drhenner template mentioned were abstracted by this option, but I have not seen it yet.

+1
source

Source: https://habr.com/ru/post/1382819/


All Articles