【问题标题】:Ruby instance connection for RedisRedis 的 Ruby 实例连接
【发布时间】:2018-09-03 04:17:15
【问题描述】:

在我的跨多个 URL 路由重用 redis 连接的代码中,这是在 Redis 中为单线程定义实例的正确方法吗?

class Red
    @conn ||= H2O::Redis.new(:host => '127.0.0.1', :port => 6379)
    class << self
      attr_reader :conn
    end
end


e.g. Route "/set"
    require "/www/test.rb"
    redis = Red.conn
    redis.set(...)

e.g. Route "/get"
    require "/www/test.rb"
    redis = Red.conn
    redis.get(...)

【问题讨论】:

  • 这行得通,你可以通过调用Red.conn.object_id看到你每次都在使用同一个对象
  • require Red 不起作用,你需要一个文件而不是一个类,而且你不应该在路由中需要,在其他地方需要
  • @maxplener,我已经编辑了代码,它是“/www/test.rb”在 H2O 网络服务器中的 MRuby 上工作。
  • @Anthony 有人建议使用“连接池”库实现,我的代码 Singleton 真的适合 Web 服务器环境吗?

标签: ruby redis


【解决方案1】:

对于在单个进程上运行的单线程 Web 服务器,这绝对是正确的方法。您不会有任何问题,因为 Ruby 的 GIL 确保不会有两行代码并行运行。

question arises 当您开始通过分叉生成多个进程时 - 因为它在修改之前共享内存。 并查看一些执行分叉的服务的文档,他们确实建议您重新建立连接: https://www.phusionpassenger.com/library/indepth/ruby/spawn_methods/#am-i-responsible-for-reestablishing-database-connections-after-the-preloader-has-forked-a-child-process

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 2020-04-02
    • 2015-11-07
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多