如何从后端同步Redis服务器和Rails数据库



我想加快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

您不需要明确提及在创建和更新展台后一小时,它将从缓存中删除它们。