Flushing Rails Database (MySQL) Sessions

December 7th, 2005

I use Rails’ database session backend for LM. (for login, as well as “flash”) Without any sort of built in garbage collection the sessions table gets very large, very quickly. Beyond aesthetic issues, this can also cause MySQL’s key buffer to fill up. (which on Debian is by default set quite low)

So I wrote up a quick flush method, and saved it in a file models/session.rb.

class CGI::Session::ActiveRecordStore::Session
  def self.flush_old_empty_sessions
     self.delete_all "DATE_SUB(NOW(),INTERVAL 6 HOUR) > 
     updated_at and BIT_LENGTH(data) <= 688"
  end
end

This says nuke all sessions which are over 6 hours old, and which are empty. (688 is the length of the serialized session with an empty flash)

MySQL specific, and susceptible to changes in either session structure or its serialization. But it was quick and easy and worked for me.

Then you simply need a cron job like: ruby script/runner 'CGI::Session::ActiveRecordStore::Session.flush_old_empty_sessions'

Tagged: Uncategorized , , , , ,

One Response to “Flushing Rails Database (MySQL) Sessions”

  1. […] [Update] 定时删除 session 有一个扩展 ActiveRecord::Session 的方法我没搞出来,后来干脆直接在 crontab 里加了一个任务,执行删除 session 的一个脚本 #!/bin/sh mysql databasename -uusername -ppassword updatedat and bitlength(data) […]