2017-10-19 8 views
0

私はファラデーと私のRuby on Railsアプリに苦労しました。 RailsのAPIコントローラはModelインスタンスを作成し、JSONでシリアル化されたこのデータを外部アプリケーションに送信します。このアプリケーションはデータを処理し、要求の数秒後に応答内にfloatという番号の応答を送信します。Ruby on Rails - 特定のレスポンスの場合ファラデーリトライリクエスト?

しかし、私のアプリは50個の個別のリクエストを送信することがあり、外部アプリは502エラー文字列を返すことがあります(実際の502 HTTPエラー!!!)。私はファラデーコールを抑制しようとしましたが、それは外部のアプリケーションを凶暴にしました。したがって、応答がこの502文字列をスローすると、リクエストを再提出する方法を見つけようとしています。私はこのためにミドルウェアを書く方法を理解していませんが、今は必要ではありません。

体内で特定の応答を受け取った場合、外部アプリにリクエストを再送信する方法を教えてもらえますか?

はここ(このメソッドはリクエストごとにトリガーされます)私のコードです:

コントローラ

def create 
    cl = Model.where(
     attr1_id: params[:attr1_id], 
     attr2_id: params[:attr2_id] 
    ).first_or_initialize(params) 
    cl.update(params) 

    # Send new Model data (in JSON) in a request to external app 
    cl_r = cl[:attr1_id] 
    r = Some_model.find_by(id: cl_r) 
    request = { :cl => cl, :r => r } 

    # Send the request 
    response = @conn.post do |req| 
     req.url '/ml' 
     req.headers['Content-Type'] = 'application/json' 
     req.headers['password'] = 'password' 
     req.body = request.to_json 
    end 

    # Get the response 
    response_json = response.body 
    response_json = response_json.gsub(/\s+/m, ' ').strip.split(" ")[1] 

    # If the response (which takes a few seconds) returns a float inside its response body 
    cl.update_attributes(response_attribute: response_json) 
    # Else 
    # Send the request that returned a 502 string inside the body to the external app again 
    # End 

    respond_with cl 
    end 

おかげで、あなたの助けを非常に歓迎です!

+0

再試行のためにドキュメントをチェックしてみましたか? http://www.rubydoc.info/github/lostisland/faraday/Faraday/Request/Retry – Maru

+0

@Maru、私のリクエストは失敗しないので、なぜ再試行はトリガーされません。応答には本体が502ありますが、HTTPヘッダーには含まれていません – Doge

+0

502を取得すると強制的に失敗するのはなぜですか?カスタム例外を再試行することができます – Maru

答えて

0

あなたは、追加情報については、documentationをチェックアウトすることができ

Faraday.new(your @conn params here if any) do |conn| 
    conn.request :retry, max: 2, interval: 0.05, 
         interval_randomness: 0.5, backoff_factor: 2 
         exceptions: [CustomException, 'Timeout::Error'] 

    response = conn.post do |req| 
     req.url '/ml' 
     req.headers['Content-Type'] = 'application/json' 
     req.headers['password'] = 'password' 
     req.body = request.to_json 
    end 

    raise CustomException if get_the_response_code == 502 


    ... 

以下のコードを試すことができます。

関連する問題