【问题标题】:Rails: Moving from Active Record Session Store to a Redis StoreRails:从 Active Record 会话存储迁移到 Redis 存储
【发布时间】:2012-08-10 01:20:36
【问题描述】:

我有一个包含数千个活动会话的大型应用程序。我想使用this 迁移到 Redis 会话存储。理想情况下,我希望我当前的会话保持活跃。

有没有人有迁移活动会话的经验。我假设我编写了迁移或 rake 任务(我认为迁移,因此我可以删除旧表作为其中的一部分),并且我只想将所有当前详细信息写入 redis。

old_sessions = ActiveRecord::Base.connection.select_all("select * from sessions")
old_sessions.each { |session| $redis.set(????? ????) }

但我担心数据完整性。

【问题讨论】:

    标签: ruby-on-rails session redis


    【解决方案1】:

    好的,经过一天的修改,这是我想出的:

    class MoveActiveRecordSesionsIntoRedis < ActiveRecord::Migration
      def up
        #get all the sessions from the last month
        old_sessions = ActiveRecord::Base.connection.select_all("select * from sessions where updated_at > '#{Time.now - 1.month}'")
    
        old_sessions.each do |session|
    
    
          #convert the base64 data back into the object
          data = ActiveRecord::SessionStore::Session.unmarshal(session["data"])
    
          #load each session into Redis, dumping the object appropriately      
          $redis.setex session["session_id"], 
                       1.month.to_i, 
                       Marshal.dump(data).to_s.force_encoding(Encoding::BINARY)
        end
    
        #drop the old session table (So long unecessary 3Gigs!)
        drop_table :sessions
      end
    
      def down
        raise ActiveRecord::IrreversibleMigration, "Session face-plant!"
      end
    end
    

    我把它放在这里作为参考。或者,如果您发现它有问题,我会全神贯注。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2013-05-07
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      相关资源
      最近更新 更多