【问题标题】:Rails Cache is storing the value but not working?Rails Cache 正在存储值但不工作?
【发布时间】:2018-08-25 22:44:35
【问题描述】:

我正在将一个外部 API 响应缓存到 Rails 中。我从缓存中读取,它按预期返回 nil 。我将它存储到缓存中,它返回 true,我再次读取它并返回我的值,但是如果我使用相同的参数从客户端发出另一个请求,它返回 nil,就好像该值没有被存储一样。

    def create
     cache = ActiveSupport::Cache::MemoryStore.new
       url = "http://api.openweathermap.org/data/2.5/weather?zip=" + params[:zip] +"&units=imperial&APPID=4e66533961b500086bf6bd7c37d4b847"
       @weather =  fetch_weather(url)
       p cache.read(params[:zip])
       weather = cache.read(params[:zip])
       p weather
       p weather.nil?
       if weather.nil?
        cache.write(params[:zip],@weather,:expires_in => 30.minutes)
       end
       p cache.read(params[:zip])

     render json: @weather
    end

例如,我将第一次使用邮政编码 94016,它会返回

nil
nil
true
<RestClient::Response 200 "{\"coord\":{\"...">

我将使用相同的邮政编码再次运行它并得到相同的响应。我在我的开发环境中启用了缓存。我不确定为什么它不起作用。谢谢。

【问题讨论】:

  • 你是如何运行你的代码的?
  • 有一个前端客户端触发控制器中的创建动作。所以前端将邮政编码作为参数传递给后端,并在表单提交时触发控制器动作

标签: ruby-on-rails caching


【解决方案1】:

因为每次您请求此操作时,您都会创建一个缓存存储:

cache = ActiveSupport::Cache::MemoryStore.new

你应该把这一行放在你的配置文件中:

config.cache_store = :memory_store, { size: 64.megabytes }

然后使用 Rails.cache 获取或设置缓存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多