一种使用 Rails 在多个 httpd 线程之间共享变量的方法?
假设我的 Rails Web 应用程序中有以下线程:
class MyController
def my_action
count = 0
arr = []
10.times do |i|
arr[i] = Thread.new {
sleep(rand(0)/10.0)
Thread.current["mycount"] = count
count += 1
}
end
arr.each {|t| t.join; print t["mycount"], ", " }
puts "count = #{count}"
end
end
如您所见,“count”变量在所有线程之间共享。
现在,我想要做的是在多个 httpd 请求中共享“计数”,并允许 MyController 中的 my_action 访问该变量。例如,也许无论生成 ruby 进程来为 httpd 进程提供服务,都可以将变量 count 保存在其范围内,然后为 httpd 进程生成的 ruby 进程就可以访问该变量。
使用 memcached、数据库和会话变量是不可能的。最终“count”实际上将是一个资源对象……一个 FTP 连接。
这可能吗?也许使用 Apache/Passenger 工作人员,如 这个?
示例代码将不胜感激。
Let's say I have the following threading in my Rails web application:
class MyController
def my_action
count = 0
arr = []
10.times do |i|
arr[i] = Thread.new {
sleep(rand(0)/10.0)
Thread.current["mycount"] = count
count += 1
}
end
arr.each {|t| t.join; print t["mycount"], ", " }
puts "count = #{count}"
end
end
As you can see, the 'count' variable is shared across all threads.
Now, what I want to do is share 'count' across multiple httpd requests and allow my_action in MyController to have access to that variable. For instance, maybe whatever spawns the ruby process to serve httpd process could hold the variable count in its scope, and then the ruby processes spawned for httpd processes could then access that variable.
Using memcached, a database, and session variables is out of the question. Ultimately 'count' will actually be a resource object...an FTP connection.
Is this possible? Perhaps using Apache/Passenger workers like this?
Example code would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用全局变量确实可以实现这一点。 Rails 中的全局变量是以美元符号开头的变量,例如 $count。
Exactly this is possible using global variables. Global variables in Rails are those that start with a dollar sign, like $count.