2

我们有一个应用程序可以对外部服务进行数百次 API 调用。有时,有些电话需要太多时间才能响应。

我正在使用rake_timeout gem 来查找耗时的过程,因此,Timeout::Error只要某些请求响应时间过长,就会抛出。我正在挽救此错误并重试该方法:

def new
 @make_one_external_service_call = exteral_api_fetch1(params[:id])
 @make_second_external_call = exteral_api_fetch1(@make_one_external_service_call)

  #Below code will be repeated in every method

 tries = 0
rescue Timeout::Error => e
  tries += 1
  retry if tries <= 3
  logger.error e.message 
end

这使该方法可以完全重新运行它。这非常冗长,我每次都在重复。

有没有办法做到这一点,如果发生Timeout:Error,它会自动重试该方法三次?

4

4 回答 4

3

我有一个小模块:

# in lib/retryable.rb
module Retryable

  # Options:
  # * :tries - Number of tries to perform. Defaults to 1. If you want to retry once you must set tries to 2.
  # * :on - The Exception on which a retry will be performed. Defaults to Exception, which retries on any Exception.
  # * :log - The log level to log the exception. Defaults to nil.
  #
  # If you work with something like ActiveRecord#find_or_create_by_foo, remember to put that call in a uncached { } block. That
  # forces subsequent finds to hit the database again.
  #
  # Example
  # =======
  #   retryable(:tries => 2, :on => OpenURI::HTTPError) do
  #     # your code here
  #   end
  #
  def retryable(options = {}, &block)
    opts = { :tries => 1, :on => Exception }.merge(options)

    retry_exception, retries = opts[:on], opts[:tries]

    begin
      return yield
    rescue retry_exception => e
      logger.send(opts[:log], e.message) if opts[:log]
      retry if (retries -= 1) > 0
    end

    yield
  end

end

而不是在你的模型中:

extend Retryable

def new
  retryable(:tries => 3, :on => Timeout::Error, :log =>:error) do
    @make_one_external_service_call = exteral_api_fetch1(params[:id])
    @make_second_external_call = exteral_api_fetch1(@make_one_external_service_call)
  end
  ...
end
于 2013-10-14T16:13:42.170 回答
2

你可以这样做:

module Foo
  def self.retryable(options = {})
    retry_times   = options[:times] || 10
    try_exception = options[:on]    || Exception

    yield if block_given?
  rescue *try_exception => e
    retry if (retry_times -= 1) > 0
    raise e
  end
end

Foo.retryable(on: Timeout::Error, times: 5) do
  # your code here
end

您甚至可以将多个异常传递给“catch”:

Foo.retryable(on: [Timeout::Error, StandardError]) do
  # your code here
end
于 2013-10-14T16:15:53.150 回答
1

我认为您需要的是可重试的宝石

使用 gem,您可以编写如下方法

def new
  retryable :on => Timeout::Error, :times => 3 do
   @make_one_external_service_call = exteral_api_fetch1(params[:id])
   @make_second_external_call = exteral_api_fetch1(@make_one_external_service_call)
  end
end

请阅读文档以获取有关如何使用 gem 及其提供的其他选项的更多信息

于 2013-10-14T16:07:11.197 回答
0

您可以为此编写一个辅助方法:

class TimeoutHelper
  def call_and_retry(tries=3)
    yield
  rescue Timeout::Error => e
    tries -= 1
    retry if tries > 0
    Rails.logger.error e.message
  end
end

(完全未经测试)并通过调用它

TimeoutHelper.call_and_retry { [your code] }
于 2013-10-14T16:07:18.397 回答