Rails缓存存储了值但不起作用?

3

我正在将一个外部 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\":{\"...">

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


你的代码是怎么运行的,确切地说? - Matt Gibson
有一个前端客户端触发控制器中的创建操作。因此,前端将邮政编码作为参数传递给后端,并在表单提交时触发控制器操作。 - Spikerr
1个回答

3

由于每次请求此操作都会创建一个缓存存储:

cache = ActiveSupport::Cache::MemoryStore.new

你应该将这行代码放入你的配置文件中:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接