【问题标题】:Rails using Redis as session store with UnicornRails 使用 Redis 作为独角兽的会话存储
【发布时间】:2014-09-28 23:02:41
【问题描述】:

我刚刚从使用 cookie 作为会话存储切换到 redis。 配置如下:

# Gemfile
gem 'redis-rails', group: :production

# config/initializers/session_store.rb
if ENV['RAILS_ENV'] == 'production'
  Rails.application.config.session_store :redis_store, redis_server: ENV['REDISCLOUD_URL'], expires_in: 60.minutes
else
  Rails.application.config.session_store :cookie_store, key: '_marketplace_session'
end

但是,我记得在设置独角兽时,我必须注意外部连接。 这是 Resque 的一个例子

before_fork do |server, worker|
  # If you are using Redis but not Resque, change this
  if defined?(Resque)
    Resque.redis.quit
    Rails.logger.info('Disconnected from Redis')
  end
end

after_fork do |server, worker|
  # If you are using Redis but not Resque, change this
  if defined?(Resque)
    Resque.redis = ENV['<REDIS_URI>']
    Rails.logger.info('Connected to Redis')
  end
end

我是否还必须在 Unicorn 配置中从 Redis 断开并重新连接?我只使用 Redis 作为会话存储,没有别的。

感谢任何输入。

【问题讨论】:

    标签: ruby-on-rails session redis


    【解决方案1】:

    由于 redis-store 使用 redis-rb,所以需要在 Unicorn fork 之后创建连接。因此,如果连接已经打开,您必须执行与 Resque 类似的操作。

    这是一个代码示例:

    after_fork do |server, worker|
      # Anything else you may have
      # ...
    
      Rails.cache.reconnect
    end
    

    重新连接的调用将确保每个进程都使用自己的 Redis 客户端。

    【讨论】:

    • 你知道怎么做吗?
    • 该代码示例在问题询问如何重新连接 session_store 时重新连接 cache_store。知道该怎么做吗?
    • 我对 Redis session_store 也有同样的问题,有没有人提出解决方案?谢谢!
    猜你喜欢
    • 2021-05-22
    • 2018-02-19
    • 2015-03-12
    • 2013-03-29
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    相关资源
    最近更新 更多