Rails: Advantages of storing session in database?
I'm just wonder开发者_运维技巧ing why storing session in database? Is there any advantage to storing session in database?
The advantage to the database or memcached is that session data cannot be tampered with on the client side and that you can store a larger amount of data than you would with cookies (4kB).
If your session is stored in cookies or the database and the web service is restarted then the session data is not lost. It may only be lost if it is stored in memcached.
If the server is load balanced then the session data is passed to the web server that is serving the request, so this is not an issue with cookies, database, or memcached sessions.
The advantage of cookies over memcached or the database is that the client stores the session data, so the server is not responsible for it.
Keep in mind that either way cookies will be passed to and from the client because a session reference still needs to be maintained.
The two reasons I can think of are that:
1) If the web service is restarted, the session data is not lost
2) In a load balanced environment, the session data is stored in a central location, meaning any server can serve the request and have access to the session data.
There are at least three reasons I can think of. If you save the session in the DB you can:
- access it easily on any Rails instance you execute. So if you have more than one machine, you don't have to worry about distributing the session data.
- You don't have the 4kb session limit session that only aplies when using cookie session store. Although you are not supposed to use the session to store objects, you may that functionality some day.
- When using and RDBM (and not Memcached, or any other non persisted storage) you don't have to worry about loosing session data.
one less obvious and small advantage to having the sessions in the database is that if you need to count current sessions and see the names of other logged in users it is easier to implement than if you were using cookies only to store session data or memcached.
another advantage is to handle session expiry on the server side as described in section 2.9:
http://guides.rubyonrails.org/security.html
"However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer."
class Session < ActiveRecord::Base
def self.sweep(time = 1.hour)
if time.is_a?(String)
time = time.split.inject { |count, unit| count.to_i.send(unit) }
end
delete_all "updated_at < '#{time.ago.to_s(:db)}' OR
created_at < '#{2.days.ago.to_s(:db)}'"
end
end
精彩评论