我想加快rails应用程序页面的加载速度,为此我使用redis。我将查询记录从数据库存储到redis服务器。在这段代码中,我检查变量是否已经存在于redis中。如果已经存在,则无需再次执行查询,否则执行查询。我已将过期时间设置为1小时,因此此redis变量将在1小时后重置。

// 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

但这里的问题是,如果数据库中的记录在1小时前被更改,它将不会实时反映。有没有redis的解决方案,可以在后台同步数据库和redis服务器数据,我们不需要提到过期时间?

最佳答案

是的,我们可以做到

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

您不需要在创建和更新booth后的一小时内明确提到它将从缓存中删除它们。

关于ruby-on-rails - 如何从后端同步Redis服务器和Rails数据库?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51558006/

10-15 08:02
查看更多