Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom CacheBackend #376

Open
diegosteiner opened this issue Dec 10, 2024 · 0 comments
Open

Custom CacheBackend #376

diegosteiner opened this issue Dec 10, 2024 · 0 comments

Comments

@diegosteiner
Copy link
Owner

Sowas:

class DynamicCacheStore
  def initialize(redis_store, fallback_store)
    @redis_store = redis_store
    @fallback_store = fallback_store
    @use_fallback = false
  end

  def fetch(name, options = {}, &block)
    active_store.fetch(name, options, &block)
  rescue => e
    handle_error(e)
    @fallback_store.fetch(name, options, &block)
  end

  def write(name, value, options = {})
    active_store.write(name, value, options)
  rescue => e
    handle_error(e)
    @fallback_store.write(name, value, options)
  end

  def read(name, options = {})
    active_store.read(name, options)
  rescue => e
    handle_error(e)
    @fallback_store.read(name, options)
  end

  private

  def active_store
    if @use_fallback
      @fallback_store
    else
      @redis_store
    end
  end

  def handle_error(error)
    Rails.logger.warn("Redis unavailable (#{error.message}), switching to fallback cache")
    @use_fallback = true
    reset_redis_after_timeout
  end

  def reset_redis_after_timeout
    Thread.new do
      sleep(30) # Wait for 30 seconds before trying Redis again
      @use_fallback = false
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant