Skip to content

Instantly share code, notes, and snippets.

@mpouleijn
Created February 16, 2012 13:24
Show Gist options
  • Save mpouleijn/1844808 to your computer and use it in GitHub Desktop.
Save mpouleijn/1844808 to your computer and use it in GitHub Desktop.
Evented Sinatra
## Eventmachine
# Non-blocking I/O event loop in Ruby
# Lots of extensions that support MySQL, AMPQ, Redis, Memcache, etc.
# Suffers from callback hell (like node.js)
# Easy to start with
require 'eventmachine'
require 'em-http-request'
EventMachine.run {
http = EventMachine::HttpRequest.new('http://google.com/').get :query => {'keyname' => 'value'}
http.errback { p 'Uh oh'; EM.stop }
http.callback {
p http.response_header.status
p http.response_header
p http.response
EventMachine.stop
}
}
## Ruby Fibers
# Allow a piece of code to yield execution at a later time (continuations)
fiber = Fiber.new do
print "1 "
Fiber.yield
print "2 "
end
fiber.resume
print "3 "
fiber.resume
# prints out "1 3 2"
## Eventmachine + Fibers = <3
# Supports a synchronous looking syntax
# Works well for a model that has a request / fiber
# Simple Example
EventMachine.run {
http = EventMachine::HttpRequest.new('http://google.com/').aget :query => {'keyname' => 'value'}
p http.response_header.status
p http.response_header
p http.response
EventMachine.stop
}
# Sinatra proxying requests to Google
require 'sinatra'
require 'rest-client'
require 'faraday'
get '/' do
Faraday.get 'http://google.com'
end
# Benchmark
# ab -c 100 -n 1000 http://127.0.0.1:4567/
# Requests per second: 39.23 [#/sec] (mean)
# Let's add Sinatra::Synchrony (https://github.com/kyledrake/sinatra-synchrony)
require 'sinatra'
require 'sinatra/synchrony'
require 'faraday'
Faraday.default_adapter = :em_synchrony #Tell Faraday to use correct EM adapter
get '/' do
Faraday.get 'http://google.com'
end
# Benchmark
# ab -c 100 -n 1000 http://127.0.0.1:4567/
# Requests per second: 732.61 [#/sec] (mean)
# Each request becomes a Fiber using Rack::FiberPool
# There are AR DB adapters for MySQL and PostgreSQL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment