Skip to content

Instantly share code, notes, and snippets.

@charger
Forked from Paxa/basic.ru
Created October 19, 2012 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save charger/3918284 to your computer and use it in GitHub Desktop.
Save charger/3918284 to your computer and use it in GitHub Desktop.
Async request handling with sinatra and EM, freeze if request not exist URL
#!/usr/bin/env rackup -Ilib:../lib -s thin
# async message handling
# using gem https://github.com/raggi/async_sinatra
require 'sinatra/async'
require "em-http-request"
require 'open-uri'
require "em-synchrony"
require "em-synchrony/em-http"
require "em-synchrony/fiber_iterator"
module Handler
extend self
@queue = []
def <<(value)
@queue << value
end
def run
return if @running
@running = true
EventMachine::PeriodicTimer.new(1) do
concurrency = 5
urls = @queue.shift(concurrency)
if urls.any?
puts "remain #{@queue.size}"
EM.synchrony do
EM::Synchrony::FiberIterator.new(urls, concurrency).each do |url|
resp = EventMachine::HttpRequest.new(url).get
if resp.response_header.status == 200
puts "Message delivered"
else
puts "Error when get #{url} status #{resp.response_header.status}"
@queue.push(url) #потом запросим повторно
end
puts "request complete #{resp.response_header.status}"
end
end
end
end
puts "Handler started"
end
end
class AsyncTest < Sinatra::Base
register Sinatra::Async
enable :show_exceptions
before do
Handler.run
end
aget '/send' do
msg=params[:http]
body "Added to queue: #{msg}"
Handler << msg
end
end
run AsyncTest.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment