Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Moving from Active Record Session Store to a Redis Store

I have a large application that as many, many thousand active sessions. I want to migrate into a Redis session store using this. And ideally, I want my current sessions to stay active.

Does anyone have any experience in migrating active sessions. I assume I write either a migration or a rake task (I think migration, so I can drop the old table as part of this), and I want to just write into redis all the current details.

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

But I am worried about data integrity.

like image 343
earnold Avatar asked Dec 11 '22 23:12

earnold


1 Answers

Alright, after a day of hacking this up, here's what I came up with:

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

I'm putting this here as a reference. Or if you see something wrong with it, I'm all ears.

like image 150
earnold Avatar answered May 12 '23 19:05

earnold