【问题标题】:Is there a way to cache objects with jsonapi-rb?有没有办法用 jsonapi-rb 缓存对象?
【发布时间】:2022-01-20 04:07:19
【问题描述】:

我知道我们应该做更多的研究,但我目前不知所措。我正在尝试使用片段缓存,但似乎找不到任何其他有关如何使用的信息。

http://jsonapi-rb.org/guides/serialization/rendering.html 声明“缓存:支持 fetch_multi 进行片段缓存的缓存”,但没有提供任何示例。

【问题讨论】:

标签: ruby-on-rails json-api


【解决方案1】:

如果您在当前测试环境中启用了缓存,那么将其添加到 cache 选项就足够了:

# app/serializers/serializable_user.rb
class SerializableUser < JSONAPI::Serializable::Resource
  type 'users'
  attributes :id, :name, :dob

  def jsonapi_cache_key(*)
    'cache_key'
  end
end

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def index
    render jsonapi: User.find(1), cache: Rails.cache
  end
end

您可能想看看this 是如何进行内部测试的。

【讨论】:

  • 所以我创建了一个新的缓存实例,即 StoreCache = ActiveSupport::Cache::RedisCacheStore.new(redis: Redis.current) 并将其作为选项传递给 JSONAPI::Rails::SuccessRenderer.new .render() 方法。我还在上面的可序列化对象中定义了 jsonapi_cache_key 但我如何判断它是否实际上是从缓存中提取的?
  • 好的,所以我可以看到它是从缓存中提取的,但它被呈现为 json 字符串而不是对象。我来看看规格。
猜你喜欢
  • 1970-01-01
  • 2012-06-27
  • 2017-03-21
  • 2019-12-17
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-09
相关资源
最近更新 更多