【问题标题】:Using EventMachine to make multiple request using same connection?使用 EventMachine 使用同一连接发出多个请求?
【发布时间】:2014-03-14 15:01:56
【问题描述】:

我有一个正在运行的 EventMachine 正在侦听 UDP 数据包。每次收到 UDP 数据包时,我都想使用 REST 调用将数据转发到某个数据库。我创建了一个 EM::Connection 子类,其中 receive_data 方法通过 REST 调用转发数据。

由于数据的频率很高,我想重用请求之间的连接(使用“keep-alive”),如果可能的话也使用管道。在不同呼叫之间共享连接的好方法是什么?

目前我的 UDPHandler 如下所示:

module Udp
  module Collector
    class UDPHandler < EM::Connection
      def receive_data(data)
        http = EventMachine::HttpRequest.new('http://databaseurl.com/').post body: data
      end
    end
  end
end

这个类调用如下:

EM.run do
  EM.open_datagram_socket('0.0.0.0', 9000, Udp::Collector::UDPHandler)
end

我曾想过将请求对象设为类变量,但我认为在事件机器的上下文中这不是一个好主意。还是这样?

【问题讨论】:

    标签: ruby udp eventmachine em-http-request


    【解决方案1】:

    我相信这样的事情应该可以工作

    module Udp
      module Collector
        class UDPHandler < EM::Connection
          def http_connection
            @http_connection ||= EventMachine::HttpRequest.new('http://databaseurl.com/')
          end
    
          def receive_data(data)
            http = http_connection.post body: data, keepalive: true
          end
        end
      end
    end
    

    但是你不能以这种方式执行并行请求,所以你需要使用某种连接池。

    没有排队和其他东西的最简单的是:

    module Udp
      module Collector
        class UDPHandler < EM::Connection
          def connection_pool
            @connection_pool ||= []
          end
    
          def get_connection
            conn = connection_pool.shift
            conn ||= EventMachine::HttpRequest.new('http://databaseurl.com/')
            conn
          end
    
          def receive_data(data)
            conn = get_connection
            request = conn.post body: data, keepalive: true
            request.callback do
              connection_pool << conn
            end
          end
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-26
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      相关资源
      最近更新 更多