0

I want to speed up rails app page loading time and I am using Redis for that. I store the query records from database to redis server. Here, in this code I check if the variable is already present in the redis or not. If it is already present, then no need to execute the query again otherwise execute the query. I have set expiration time as 1 hour, so this redis variable will get reset after 1 hour.

// Booths controller
class BoothsController < ApplicationController
  def new_booth
    @booth_package_types = fetch_package_type
  end
end

// Booth helper
module BoothsHelper
  def fetch_package_type
    package_types_booth =  $redis.get("package_types_booth") rescue nil
    if package_types_booth.nil?
      package_types_booth = PackageType.all.to_json
      $redis.set("package_types_booth", package_types_booth)
      $redis.expire("package_types_booth",1.hour.to_i)
    end
    @package_types_booth = JSON.load package_types_booth
  end
end

But the problem here is that if the records in the DB has been changed before 1 hour, it will not reflect in real time. Is there any solution with Redis which will synchronize the database and Redis server data in the backend and we don't need to mention the expiration time?

1

1 Answer 1

1

Yes we can achieve these

class BoothsController < ApplicationController
  def new_booth
    @booth_package_types = fetch_package_type
  end
end

// Booth helper
module BoothsHelper
  def fetch_package_type
    package_types_booth =  $redis.get("package_types_booth")
    if package_types_booth.nil?
      package_types_booth = PackageType.all.to_json
      $redis.set("package_types_booth", package_types_booth)
    end
    @package_types_booth = JSON.load package_types_booth
  end
end

#booth.rb file
class Booth < ApplicationRecord
  after_save :clear_cache

  def clear_cache
    $redis.del "package_types_booth"
  end
end

You do not need to mention explicitly hour after create and update of booth it will remove them from cache.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.