为使用persistent_http进行特定API调用扩展HTTParty RestClient的最佳方法是什么?

问题描述 投票:0回答:2

我们目前在Rails Engine中的RestClient类中使用HTTParty gem。最近,我们利用persistent_httparty包装器添加了设置读取超时和打开超时的功能。这样一来,我们便可以为长API调用实现自己的自定义处理。

我们的代码类似于RestClient类:

require 'httparty'
require 'persistent_httparty'

module ScheduleEngine
  class RestClient
    include HTTParty

    pool_size = 10
    idle_timeout = 10
    keep_alive = 10
    read_timeout = 3
    open_timeout = 3

    persistent_connection_adapter(pool_size: pool_size, idle_timeout: idle_timeout, keep_alive: keep_alive,
                                  read_timeout: read_timeout, open_timeout: open_timeout)

    class << self
      # other stuff
    end

    # other code omitted for brevity
  end
end

然后,要使用此RestClient,我们只需在需要进行API调用的地方实例化RestClient。

client = RestClient.new(user, params)

data = client.callAPI()

现在,我们希望某些特定的API调用不具有读取超时或打开超时。

我不是Ruby专家,但我的最初想法是创建一个继承自RestClient类的新类。但这只会覆盖一些基本值。下面是一个示例:

module ScheduleEngine
  class SpecialRestClient < RestClient
    pool_size = 10
    idle_timeout = 10
    keep_alive = 10

    # Note that I'm no longer providing read_timout or open_timeout
    persistent_connection_adapter(pool_size: pool_size, idle_timeout: idle_timeout, keep_alive: keep_alive)
  end
end

有了这个新的类,我可以在不需要读取超时或打开超时的地方简单地实例化它。

我的问题是,这是一个好方法吗?还是有更好的方法?

ruby-on-rails ruby httparty persistent-connection
2个回答
0
投票

关于在此处添加初始化程序,这将花费超时哈希?像:

def initialize(timeouts = {})
@timeouts = timeouts
end

def call
persistent_connection_adapter({pool_size: 10, idle_timeout: 10, keep_alive: 10}.merge(timeouts))
end

因此,如果您要设置超时,只需在初始化时定义。


0
投票

鉴于HTTParty的工作方式,我不确定您的建议是否会起作用。看起来,从遍历代码库的短代码开始,通过调用read_timeoutopen_timeout等,您正在设置默认选项,然后将选项传递给persistent_connection_adapter这些正在被合并到“ default_options”中

这意味着即使您从新的类中删除了对read_timeoutopen_timeout的方法调用,它们仍然会在继承中滴入。

仅配置默认选项,然后将变量选项传递给persistent_connection_adapter可能更有意义例如:

 class RestClient
   include HTTParty
   pool_size = 10
   idle_timeout = 10
   keep_alive = 10
   persistent_connection_adapter(read_timeout: 3, open_timeout: 3)
end 

这意味着您可以在仍然为该特定类配置连接选项的同时继承:

 class SpecialRestClient < RestClient
   persistent_connection_adapter
 end 
© www.soinside.com 2019 - 2024. All rights reserved.