2012-08-13 99 views
3

我有一個大型應用程序,可以存儲多達數千個活動會話。我想使用this遷移到Redis會話存儲中。理想情況下,我希望我的當前會話保持活躍。Rails:從活動記錄會話存儲轉移到Redis存儲

有沒有人在遷移活動會話方面有任何經驗。我假設我寫了一個遷移或rake任務(我認爲遷移,因此我可以刪除舊錶作爲其中的一部分),並且我只想寫入redis所有當前的詳細信息。

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

但是我很擔心數據的完整性。

回答

12

好吧,黑客這個了一整天后,這裏就是我想出了:

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 

我把這個在這裏作爲參考。或者,如果你看到有什麼問題,我全都是耳朵。