Upgrade to Pro — share decks privately, control downloads, hide ads and more …

キャッシュを利用してRailsアプリの処理を高速化する

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for yuki21 yuki21
October 16, 2020

 キャッシュを利用してRailsアプリの処理を高速化する

5分間社内LT資料

Avatar for yuki21

yuki21

October 16, 2020
Tweet

More Decks by yuki21

Other Decks in Programming

Transcript

  1. CacheStoreにRedisを設定する # config/environments/development.rb config.cache_store = :redis_cache_store, { url: ENV["REDIS_URL"], expires_in:

    24.hours.to_i } cache_storeにRedisを設定します。 今回はローカル環境で動作の確認をするのでdevelopment.rbで設定をしました。
  2. 実際に利⽤してみる ほとんど更新のないカテゴリ⼀覧をキャッシュしてみます。 # Cache を利⽤しない状態 class CategoriesController < ApplicationController def

    index category = Category.all render status: 200, json: category, each_serializer: CategorySerializer end end # Cache を利⽤した場合 def index render status: 200, json: cached_categories end def cached_categories Rails.cache.fetch("categories", expires_in: 24.hours) do category = Category.all render_to_string json: category, each_serializer: CategorySerializer end end
  3. 実⾏結果 Started GET "/v1/categories" for ::1 at 2020-10-16 15:06:44 +0900

    Processing by V1::CategoriesController#index as HTML Category Load (12.3ms) SELECT DISTINCT `categories`.* FROM `categories` ... ↳ app/controllers/v1/categories_controller.rb:10:in `block in cached_categories' [active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Json (9.24ms) Completed 200 OK in 125ms (Views: 1.0ms | ActiveRecord: 32.0ms | Allocations: 48349) Started GET "/v1/categories" for ::1 at 2020-10-16 15:06:52 +0900 Processing by V1::CategoriesController#index as HTML Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms | Allocations: 226) ActiveRecordの読み込みとActiveModelSerializersによるレンダリングがキャッシュによって 省略されました。
  4. リクエストパラメータをkeyにしてキャッシュする リクエスト毎に結果が異なる場合、cache_keyをユニークな値で定義します。 def show if cached_supplier render status: 200, json:

    cached_supplier else render status: 404, json: Error.new(message: "Not found"), serializer: ErrorSerializer end end def cached_supplier cache_key = "supplier-#{params[:id]}" Rails.cache.fetch(cache_key, expires_in: 1.hours) do supplier = Supplier.includes(:category).find_by(supplier_code: params[:id]) if supplier.present? render_to_string json: supplier, serializer: SupplierSerializer else # ステータスを404 としてキャッシュできなかったのでnil を返す nil end end end