简体   繁体   中英

Rails Resque to run background job - How it speeds up the App

I followed this tutorial about Resque on Raiscast: http://railscasts.com/episodes/271-resque

In the tutorials, there is an example about a code highlighter that resides in the #create method in controller:

def create
  @snippet = Snippet.new(params[:snippet])
  if @snippet.save
    uri = URI.parse('http://pygments.appspot.com/')
    request = Net::HTTP.post_form(uri, {'lang' => @snippet.language, 'code' => @snippet.plain_code})
    @snippet.update_attribute(:highlighted_code, request.body)
    redirect_to @snippet, :notice => "Successfully created snippet."
  else
    render 'new'
  end
end

It is said that

"Communicating with external services through a Rails request is generally a bad idea as they might be slow to reply and so tie up your entire Rails process and any other requests that trying to connect to it. It's much better to move external requests out into an external process. We'll set up Resque so that we can move the request into a Resque worker."

What it wants to say is that: Resque helps speed up the Rails app. However, I don't quite understand why/how moving that piece of code out of the controller speed up the app. It looks for me just moving it from the controller to another library. Can anyone explain to me?

If you look at what the application is doing, it is calling an external application (pygments.appspot.com) to perform the highlighting.

Let's assume that this site is quite popular and as a result is taking 20 seconds to respond. With the code as it is in the controller, your application will take the time it takes for you to process the response, plus the 20 seconds from pygments before your user sees the response.

When you move this into a background job, those 20 seconds now happen in the background and the user will be able to see the response but without the syntax highlighting. If they refresh in 20 seconds when the highlighting is done, then they will see it.

So to answer your question, moving the code somewhere else in the application isn't what speeds it up. The code does not run any faster. Moving the code to a background job means that the implications on the speed don't affect the response time to the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM