Pergunta

Problema: Eu tenho vários sidekiq threads e uma função que pode ser chamada apenas uma vez no tempo a partir de qualquer uma das threads.

Motivo: Estamos consultando o API do google AdWords para obter alguns dados.Eles são bastante restritivas quando se trata de limites de velocidade.Apenas um dos segmentos pode chamar a função para obter dados de cada vez.

Agora alguns códigos:

# Public: Get estimates for a set of keywords. If there is an error, retry
# several times. If not successful, raise an error
#
# keywords: The keyword objects to get estimates for.
# save: Boolean to indicate whether the keyword objects should be saved to
# the database
#
def repeatedly_try_get_estimates(keywords: [], save: true, sleep_delay: 150)
  return keywords if keywords.empty?
  func = -> { get_estimates(keywords, !save) }
  retry_operation(function: func, max_tries: 15, sleep_delay: sleep_delay)
end
  • Como você pode ver, agora eu tenho um enorme sleep_delay contornar o problema.
  • O código chama o retry_operation função com o get_estimates função como parâmetro.Em seguida, ele irá repetir o get_estimates função várias vezes, até que haja uma API exceção.

O retry_function:

# Private: Retry a function X times and wait X seconds. If it does not work X times,
# raise an error. If successful return the functions results.
#
# - max_tries: The maximum tries to repeat the function
# - sleep_delay: The seconds to wait between each iteration.
# - function: The lambda function to call each iteration
#
def retry_operation(max_tries: 5, sleep_delay: 30, function: nil, current_try: 0, result: nil)

  # Can't call, no function
  if function.nil?
    return
  end

  # Abort, tried too frequently.
  if current_try > max_tries
    raise "Failed function too often"
  end

  # Check if there is an exception
  exception = true
  begin
    result = function.call
    exception = false
  rescue => e
    Rails.logger.info "Received error when repeatedly calling function #{e.message.to_s}"
  end

  if exception
    sleep sleep_delay if sleep_delay > 0
    retry_operation(max_tries: max_tries, sleep_delay: sleep_delay, function: function, current_try: current_try + 1)
  else
    result
  end
end

O get_estimates_function está aqui: https://gist.github.com/a14868d939ef0e34ef9f.Ele é muito longo, apenas no caso.

Eu acho que eu preciso para fazer o seguinte:

  1. Ajustar o código no repeatedly_try_get_estimates função.
  2. Use um mutex na classe.
  3. Resgatar a exceção se o mutex está em uso.
  4. Só se o mutex é livre, executar o rety_operation, mais dormir algum tempo

Obrigado pela sua ajuda :)

Foi útil?

Solução

Vamos lá, tenho que trabalhar:

# Public: Get estimates for a set of keywords. If there is an error, retry
# several times. If not successful, raise an error
#
# keywords: The keyword objects to get estimates for.
# save: Boolean to indicate whether the keyword objects should be saved to
# the database
#
def repeatedly_try_get_estimates(keywords: [], save: true, sleep_delay: 40)
  return keywords if keywords.empty?
  func = -> { get_estimates(keywords, save_keywords: true) }
  exception = nil
  result = nil
  initial_sleep = 0

  estimates_mutex.synchronize do
    since_last_request = Time.now.to_i - last_adwords_api_request
    if since_last_request <= 30
      Rails.logger.info "AdWords: Last request was only few seconds ago - sleeping #{since_last_request}."
      initial_sleep = since_last_request
    end
    begin
      result = retry_operation(function: func, max_tries: 15, sleep_delay: sleep_delay, initial_sleep: initial_sleep)
    rescue => e
      exception = e
    end
    @@last_adwords_api_request = Time.now.to_i
  end
  if exception
    raise exception
  end
  result
end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top