Created
April 18, 2011 22:33
-
-
Save hungryblank/926401 to your computer and use it in GitHub Desktop.
Comparison between sync/async solutions for simple web api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# to be used with the sync version | |
require './request_handler_sync' | |
run Sinatra::Application |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# completely async version built with | |
# https://github.com/igrigorik/em-synchrony | |
# and | |
# https://github.com/postrank-labs/goliath | |
require 'goliath' | |
require 'em-synchrony' | |
require "em-synchrony/em-redis" | |
class FbRequest | |
HOST = "127.0.0.1" | |
class << self | |
def connection | |
@connection ||= begin | |
EventMachine::Synchrony::ConnectionPool.new(size: 2) do | |
EM::Protocols::Redis.connect(:host => HOST) | |
end | |
end | |
end | |
def create! | |
new.save | |
end | |
end | |
def initialize | |
@recipient = 'foo' | |
@sender = 'bar' | |
end | |
def save | |
next_id = connection.incr('counter').to_s | |
10.times do |n| | |
connection.sadd(@sender + next_id, @recipient + n.to_s) | |
end | |
connection.expire(@sender + next_id, 120) | |
connection.smembers(@sender + next_id) | |
end | |
def connection | |
self.class.connection | |
end | |
end | |
class RequestHandlerAsync < Goliath::API | |
def response(env) | |
req = FbRequest.create! | |
[200, {"Content-Type" => "text/html"}, req.inspect] | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# sync version using sinatra | |
require 'sinatra' | |
require 'redis' | |
class FbRequest | |
HOST = '127.0.0.1' | |
class << self | |
def connection | |
@connection ||= Redis.new(:host => HOST) | |
end | |
def create! | |
new.save | |
end | |
end | |
def initialize | |
@recipient = 'foo' | |
@sender = 'bar' | |
end | |
def save | |
next_id = connection.incr('counter').to_s | |
10.times do |n| | |
connection.sadd(@sender + next_id, @recipient + n.to_s) | |
end | |
connection.expire(@sender + next_id, 300) | |
connection.smembers(@sender + next_id) | |
end | |
def connection | |
self.class.connection | |
end | |
end | |
get "/requests/new" do | |
FbRequest.create! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment