問題一覧に戻る
上級パフォーマンスと本番環境
問題69: キャッシュ戦略 - Redis/Memcached
RedisまたはMemcachedを使用してキャッシュ戦略を実装し、アプリケーションのパフォーマンスを向上させる方法を学習します。データベースクエリ、計算値、APIレスポンス、レンダリングされたビューをキャッシュして、負荷を軽減し応答時間を短縮します。
# config/environments/production.rb
# キャッシュストアを設定
config.cache_store = :,
{ url: ENV['REDIS_URL'] }
# Controller
def expensive_calculation
# リードスルーキャッシュパターン
Rails.cache. "user_stats_#{@user.id}" do
@user.calculate_statistics
end
end
# キャッシュ有効期限を設定
Rails.cache.fetch "posts_#{page}", : 1.hour do
Post.published.page(page)
end
# 特定のキャッシュキーをクリア
Rails.cache. "user_stats_#{user.id}"