2011-10-27 42 views
0

我運行一個簡單的瘦服務器,即發佈一些消息給不同的隊列,代碼如下:的Ruby AMQP

require "rubygems" 
require "thin" 
require "amqp" 
require 'msgpack' 

app = Proc.new do |env| 

params = Rack::Request.new(env).params 

command = params['command'].strip rescue "no command" 
number = params['number'].strip rescue "no number" 

p command 
p number 

AMQP.start do 
    if command =~ /\A(create|c|r|register)\z/i 
    MQ.queue("create").publish(number) 
    elsif m = (/\A(Answer|a)\s?(\d+|\d+-\d+)\z/i.match(command)) 
    MQ.queue("answers").publish({:number => number,:answer => "answer" }.to_msgpack) 
    end 
end 

[200, {'Content-Type' => "text/plain"} , command ] 

end 

Rack::Handler::Thin.run(app, :Port => 4001) 

現在,當我運行的服務器,這樣做http://0.0.0.0:4001/command=r&number=123123123 我一直都想與重複的輸出,是這樣的:

「沒有命令」 「無號碼」 「沒有命令」 「無號碼」

第一屆這就是爲什麼我變得像重複請求?這與瀏覽器有關嗎?因爲當我使用捲曲時,我沒有相同的行爲,爲什麼我無法獲得參數?

關於這種服務器的最佳實施任何提示將不勝感激提前

感謝。

回答

0

第二個請求來自瀏覽器尋找favicon.ico。您可以在您的處理程序添加以下代碼檢查的要求:

params = Rack::Request.new(env).params 
p env # add this line to see the request in your console window 

另外,您可以使用Sinatra

require "rubygems" 
require "amqp" 
require "msgpack" 
require "sinatra" 

get '/:command/:number' do 
    command = params['command'].strip rescue "no command" 
    number = params['number'].strip rescue "no number" 
    p command 
    p number 
    AMQP.start do 
     if command =~ /\A(create|c|r|register)\z/i 
      MQ.queue("create").publish(number) 
     elsif m = (/\A(Answer|a)\s?(\d+|\d+-\d+)\z/i.match(command)) 
      MQ.queue("answers").publish({:number => number,:answer => "answer" }.to_msgpack) 
     nd 
    end 
    return command 
end 

,然後在命令行中運行ruby the_server.rb啓動HTTP服務器。

+0

感謝您的迅速反應。你似乎是對的,有沒有辦法消除這種行爲?是否有任何使用Thin with AMQP的例子,這是使用它的最佳優化方式,無論如何,對於p env的輸出:https://gist.github.com/78208470bfffbef400fe – eki

+0

只是一個附註:你使用的是實際上是'rack',一個抽象層/中間件,用於在不同的Web服務器上運行Web應用程序,'thin'則是運行你的機架應用程序的實際網絡服務器。 「機架amqp」你可能會有更多的成功搜索結果。你也應該看看像Bunny這樣的更高級別的AMQP寶石:https://github.com/ruby-amqp/bunny。希望有所幫助。 – Matt