gpt4 book ai didi

ruby-on-rails - 如何从后端同步 Redis 服务器和 Rails 数据库?

转载 作者:可可西里 更新时间:2023-11-01 11:15:09 24 4
gpt4 key购买 nike

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

但是这里的问题是,如果DB中的记录在1小时之前发生了变化,是不会实时反射(reflect)的。 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

您无需在创建和更新展位后明确提及小时,它会将它们从缓存中删除。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com