Rails 5 API低级缓存

时间:2018-08-04 22:18:22

标签: ruby-on-rails ruby caching rails-api

我对Rails API缓存有些困惑。我正在使用JSONAPI规范和fast_jsonapi gem并尝试在表演动作中缓存车辆本身,如果有类似include=service_notes,service_alerts这样的参数出现,那么我也想缓存它们。这是我最初的方法,但不确定是否正确。

我有2个主要问题:

  1. 对于车辆缓存本身,有一种比我的车辆= Vehicle.find_cached(params [:id])更好的方法。如果未更新载具,则不使用updated_at,而是使用保存后回调来更新缓存。我只是看不到是否可以像这里建议的那样使用Rails.cache.fetch(["vehicles", vehicle], version: vehicle.updated_at)之类的东西:https://github.com/rails/rails/pull/29092,因为这需要车辆实例。如您所见,set_vehicle控制器方法很尴尬。

  2. 这个Rails.cache.fetch(['vehicles', vehicle, include_params], version: vehicle.updated_at)有意义吗?我正在尝试基于不同的包含参数来缓存查询。也许这是矫kill过正,我可以包括所有内容并将其缓存为:

    Rails.cache.fetch(['vehicles,vehicle,'with_includes'],version:vehicle.updated_at)做   Vehicle.includes(:vehicle_alerts,:service_notes,:service_intervals).find(params [:id]) 结束

在这里处理缓存的正确方法是什么?

service_note.rbservice_interval.rbvehicle_alert.rb的设置相同

class ServiceNote < ApplicationRecord
  belongs_to :vehicle, touch: true
end

vehicle.rb

class Vehicle < ApplicationRecord
  after_save :update_cache
  has_many :vehicle_alerts, dependent: :delete_all
  has_many :service_notes, dependent: :delete_all
  has_many :service_intervals, dependent: :delete_all

  def update_cache
    Rails.cache.write(['vehicles', vehicle_id], self)
  end

  def self.find_cached(vehicle_id)
    Rails.cache.fetch(['vehicles', vehicle_id]) { find(vehicle_id) }
  end
end

vehicles_controller.rb

before_action :set_vehicle, only: [:show]

def show
  render json: VehicleSerializer.new(@vehicle, options).serialized_json
end

private

def set_vehicle
  vehicle = Vehicle.find_cached(params[:id])

  @vehicle = Rails.cache.fetch(['vehicles', vehicle, include_params], version: vehicle.updated_at) do
    Vehicle.includes(include_params).find(params[:id])
  end

  authorize @vehicle
end

vehicle_serializer.rb(带有fast_jsonapi gem)

# same for :service_notes and :vehicle_alerts
has_many :service_intervals do |vehicle, params|
  if params[:include] && params[:include].include?(:service_intervals)
    vehicle.service_intervals
  end
end

0 个答案:

没有答案