开发者

Is there one Rack app instance per HTTP request?

I'm building a Facebook app called Lovers, using a Sinatra app on Heroku. It's running on Ruby 1.9.2 on Heroku's bamboo-mri-1.9.2 stack.

It's a modular Sinatra app, and in the Lovers source cod开发者_如何学Pythone, I'm giving each instance of the Sinatra app (Lovers::Application) an instance of Facebook::Application:

require 'sinatra/base'

class Lovers::Application < Sinatra::Base
  attr_reader :facebook

  def initialize(app=nil)
    @facebook = Facebook::Application.new(
      Lovers::Conf.fb_app_id,
      Lovers::Conf.fb_app_secret,
      Lovers::Conf.fb_canvas_name)
    super(app)
  end
  # ...
end

That way, you can do Lovers.application.facebook to access the Facebook::Application instance from anywhere within the Lovers module, say from Lovers::User.

Does this make sense, or should I just have all instances of Lovers::Application (if there's ever more than one) share the same Facebook::Application instance, i.e., Lovers.facebook. That's what we're doing for Redis: Lovers.redis, which makes sense to me. I guess I'm leaning toward changing it to the latter, but I want to make sure before I change it. What do you think?

Finally, is there one instance of Lovers::Application per HTTP request?

UPDATE:

I read up on Heroku Dynos. Apparently, each dyno (process) runs an instance of Lovers::Application. So, after reading about sharing a global variable among processes, I think that means that if I define a class variable @@hit_count in the Lovers::Application class, it will have different values depending on which dyno receives the request, assuming I increment @@hit_count every time the home page is requested, i.e.:

  @@hit_count = 0

  get "/" do
    @@hit_count += 1
  end


"Finally, is there one instance of Lovers::Application per HTTP request?"

There's one instance per process/dyno.

"it will have different values depending on which dyno receives the request, assuming I increment @@hit_count every time the home page is requested"

yes, if you need global state you have to keep the state outside of your process/dyno. There are many different ways to do this, and which you choose will depend on the details of your app and your traffic levels. If you don't get a lot of traffic you can do something as simple as keeping it in your database. You can do atomic increments in postgres or mysql for something like hit_count. However, this approach may become a bottleneck if you have a lot of traffic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜