在我的项目中,我正在使用以下小型库与外部服务进行交互:
class ExternalServiceInteraction
include Singleton
URL = Rails.env.production? ? 'https://first.production.url.com' : 'http://sandbox.url.com'
API_KEY = Rails.env.production? ? 'qwerty' : 'qwerty'
DOMAIN = Rails.env.production? ? 'prod.net' : 'stage.net'
def connection
conn = Faraday.new(url: URL) do |faraday|
faraday.response :logger # log requests to STDOUT
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
end
def return_response(item=true)
if @resp.status == 200
response = item ? Hash.from_xml(@resp.body)['xml']['item'] : Hash.from_xml(@resp.body)['xml']
else
response = Hash.from_xml(@resp.body)['xml']['error']
Rails.logger.info "response_error=#{response}"
end
response
end
def get_subscribers
path = 'subscribers'
data = { 'X-API-KEY' => API_KEY, 'domain' => DOMAIN }
@resp = connection.get(path, data)
return_response
end
def get_subscriber(physical_id)
path = 'subscriber'
data = { 'X-API-KEY' => API_KEY, 'Physical_ID' => physical_id, 'domain' => DOMAIN }
@resp = connection.get(path, data)
return_response
end
# and so on
end
现在我想使用'https://second.production.url.com'如果通过第一个网址与交互服务有任何错误,那么如何更好地设置它?
起初我试图ping /从服务器获得200 ok,如果失败,我切换到第二个URL。但是有些情况下服务器启动并运行,返回200 OK,但API无法访问。我的主要问题是我不知道如何捕获错误并使用库中的其他URL重新运行方法。
答案 0 :(得分:1)
创建一个ExternalServiceInteractionWithoutFallback
,它将接受构造函数中的URL。然后,将所有API方法移至此方法,并在ExternalServiceInteraction
中使用method_missing
捕获所有API方法并委托给ExternalServiceInteractionWithoutFallback
的“活动”实例,如果调用失败,则更改您委派的实例。
答案 1 :(得分:0)
我为这种情况编写了自己的HostBackup法拉第中间件。 欢迎您使用它! https://github.com/dpsk/faraday_middleware 这是一篇文章:http://nikalyuk.in/blog/2013/06/25/faraday-using-backup-host-for-remote-request/