Skip to content

5. SQL ActiveRecord SQL Cache Strategy

Jean Luis Urena edited this page Jan 9, 2025 · 6 revisions

Summary

ActiveCachedResource supports a caching strategy in which responses are cached in a SQL database such as MySQL, PostgreSQL, Oracle, SQLite, MSSQL, and MariaDB.

Usage

  1. Setup your caching table using the built in Rails generator: bundle exec rails generate active_cached_resource:active_record
    • This will create a migration file with required columns and indexes.
    • Any additional columns/indexes/schema changes to table, must be done after this migration.
  2. Run migration: bundle exec rails db:migrate
  3. Configure your ActiveCachedResource model to use cache_strategy: active_record_sql and your Rails model.
    class CachedRemoteResource < ActiveRecord::Base
      self.table = "active_cached_resources"
      self.primary_key = "key"
    end
    
    class RemoteResource < ActiveResource::Base
      cached_resource(
        enabled: true,
        cache_store: CachedRemoteResource,
        cache_strategy: :active_record_sql,
        cache_key_prefix: "my_resource",
        logger: Rails.logger,
        ttl: 3600
      )
    end

Tips

  • Clean up the table often as active_record_sql built in strategy only deletes records through transactional cache invalidation.

Clone this wiki locally