What method should be used for rails session storage? How to decide?
What is the best method for storing session data on rails? Obviously it depends on your needs but what are the key factors that go into the decision and what are the i开发者_运维技巧deal session stores for different scenarios?
Security should be a concern. Bear in mind that anything stored on the client side (such as cookies, form POST parameters, GET parameters, etc.) can be modified using browser proxies. So, always validate anything that comes back up through the browser. You could encrypt the values in the cookies or form POST parameters as wel. Also, as Steve mentioned, cookies should generally be used only for small values.
The default file based method is very good if you're not going to be running on a cluster of servers, or if you are, if you can tolerate users' sessions getting lost if a server goes down (they would have to log back in). For the vast majority of apps, this is perfectly acceptable. You'll need to configure your load balancer for "sticky sessions", which means that a given user is bound to a single server. This can make load balancing a bit more difficult though, as you'll sometimes find that many users are bound to a single server while another server sits there idle.
If you require shared session state across the cluster, you have a couple of primary options. If your traffic is not extreme, and you can deal with a short bit of extra latency, then you can store your session information in the database. As long as your database is up, the session data won't be lost. If your database is down, well, the session data is probably the least of your worries. If your app has very high traffic, or is incredibly performance critical, then your best bet would be to use a distributed cache, such as memcached. This is extra "infrastructure" that you're going to have to maintain and monitor, however. Even if memcached is distributed, it's still an extra point of failure you're adding to your application's environment. So, don't take this lightly if you don't really need it.
To make a long story short, I'd say the default file based session storage approach is probably perfectly acceptable for 90+% of applications.
For almost every scenario, cookies are the best. They are simple in that they only depend on the fact that a server process is responding and that the user's browser works as browsers do.
Cookies are not good for storing large amounts of data or data that should be hidden from the user, but that just means that you should not put such things in the session. That's not usually a problem, so long as you keep this restriction in mind.
精彩评论