【问题标题】:Ruby AMQP under Thin HTTP serverThin HTTP 服务器下的 Ruby AMQP
【发布时间】:2011-10-27 08:15:57
【问题描述】:

我正在运行一个简单的瘦服务器,它将一些消息发布到不同的队列,代码如下:

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 之类的操作时 我总是得到重复的输出,比如:

“没有命令” “没有号码” “没有命令” “没有号码”

第一件事是为什么我会收到重复的请求?它与浏览器有关吗?因为当我使用 curl 时,我没有相同的行为,第二件事为什么我无法获得参数?

任何关于这种服务器的最佳实现的提示将不胜感激

提前致谢。

【问题讨论】:

    标签: ruby rabbitmq amqp thin


    【解决方案1】:

    第二个请求来自寻找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服务器。

    【讨论】:

    • 感谢马特的快速回复。你似乎是对的,有没有办法消除这种行为?是否有任何使用 Thin 和 AMQP 的示例,这是使用它的最佳优化方式,无论如何对于 p env 的输出:gist.github.com/78208470bfffbef400fe
    • 附带说明:您使用的实际上是 rack,一个用于在不同 Web 服务器上运行 Web 应用程序的抽象层/中间件,而 thin 是运行您的机架应用程序的实际 Web 服务器.您在谷歌上搜索“rack amqp”可能会更成功。此外,您还应该看看像 Bunny 这样的高级 AMQP gem 之一:github.com/ruby-amqp/bunny。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2013-05-26
    • 1970-01-01
    相关资源
    最近更新 更多