Rails 使用 ActiveSupport::Cache::MemoryStore 在两次 api 调用之间保存变量(控制器方法)
Rails using ActiveSupport::Cache::MemoryStore to save variable between two api calls (controller methods)
我有 APIs,我想在其中保存一些可以在每个 API 方法之间访问的值,因此我正在尝试使用 ActiveSupport::Cache::MemoryStore。我可能没有正确使用 MemoryStore(从未使用过,找不到具体的教程)
我是否正确使用了 MemoryStore?看起来应该超级简单,但似乎无法保存任何值。
class MyController
# 1st API handler /post
def first
@cache = ActiveSupport::Cache::MemoryStore.new() if @cache.nil?
@cache.write('shared_val', params['user_key'])
end
# 2nd API handler /post
def second
@cache = ActiveSupport::Cache::MemoryStore.new() if @cache.nil?
saved_val = @cache.read('shared_val')
puts "#{saved_val}" # nil?????
end
我也尝试了一些在 SO answers 中看到的示例,但似乎仍然无法保存该值。
# In config file
config.cache_store = :memory_store
# 1st API handler /post
def first
Rails.cache.write("ABC", "abc")
check_val = Rails.cache.read('ABC')
puts "VALUE: #{check_val}" # shows correct 'abc'
end
# 2nd API handler /post
def second
Rails.cache.fetch("ABC") # gets nil, why???
Rails.cache.read("ABC) # also nil
end
config.action_controller.perform_caching
默认为 false。您需要在其他环境中打开它。
我有 APIs,我想在其中保存一些可以在每个 API 方法之间访问的值,因此我正在尝试使用 ActiveSupport::Cache::MemoryStore。我可能没有正确使用 MemoryStore(从未使用过,找不到具体的教程)
我是否正确使用了 MemoryStore?看起来应该超级简单,但似乎无法保存任何值。
class MyController
# 1st API handler /post
def first
@cache = ActiveSupport::Cache::MemoryStore.new() if @cache.nil?
@cache.write('shared_val', params['user_key'])
end
# 2nd API handler /post
def second
@cache = ActiveSupport::Cache::MemoryStore.new() if @cache.nil?
saved_val = @cache.read('shared_val')
puts "#{saved_val}" # nil?????
end
我也尝试了一些在 SO answers 中看到的示例,但似乎仍然无法保存该值。
# In config file
config.cache_store = :memory_store
# 1st API handler /post
def first
Rails.cache.write("ABC", "abc")
check_val = Rails.cache.read('ABC')
puts "VALUE: #{check_val}" # shows correct 'abc'
end
# 2nd API handler /post
def second
Rails.cache.fetch("ABC") # gets nil, why???
Rails.cache.read("ABC) # also nil
end
config.action_controller.perform_caching
默认为 false。您需要在其他环境中打开它。