Thread.current[] 值和类级别属性在 Rails 中使用安全吗?
我正在尝试在 Rails 3 应用程序中解决一个特定问题,我看到的两个常见解决方案是:
Thread.current[:something] = value
和
class Foo
cattr_accessor :bar
end
Foo.bar = value
这些方法吗同时向我的 Rails 应用程序发出请求的多个用户之间的数据存储(以及相应的检索)是否安全?
我担心 Thread.current,因为 Web 服务器可以使用单个线程来服务多个请求,对吗?或者是否有一些 Rails 处理线程的方式可以防止使用 Thread.current 时出现问题?我看到 Acts As Current 使用 Thread.current 来存储当前用户,这给了我希望......但我想要权威的确认。
我还担心生产环境中的类级别属性,因为出于性能原因,我希望 Rails 将类对象缓存在内存中。类级别属性是否会在请求之间重复使用?或者由于 Rails 跨请求处理类属性的某些操作是否安全?我再次希望得到权威机构的证实。
...这个应用程序使用 Ruby 1.9.2@p180 和 Rails 3.0.9
I have a particular problem I'm trying to solve in a rails 3 app, and the two common solutions that I'm seeing are these:
Thread.current[:something] = value
and
class Foo
cattr_accessor :bar
end
Foo.bar = value
Are these methods of data storage (and the corresponding retrieval) safe across multiple users making a request to my rails app, at the same time?
I'm concerned about Thread.current, because a web server could use a single thread to serve up multiple requests, right? Or is there something in the way rails handles threads to prevent problems when using Thread.current? I see Acts As Current uses Thread.current to store the current user, so that gives me hope... but I want authoritative confirmation.
I'm also concerned about class level attributes in a production environment, because I would expect rails to cache class objects in memory, for performance reasons. Does a class level attribute get re-used across requests? or is it safe due to something that rails does to handle class attributes across requests? again, i would like authoritative confirmation of this.
... this app uses Ruby 1.9.2@p180, with Rails 3.0.9
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
足够安全,可以存储当前请求的时区:
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/time/zones.rb
Safe enough to store the time zone of the current request:
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/time/zones.rb