LoginSignup
3
9

More than 5 years have passed since last update.

Rubyの並列HttpリクエストGem Typhoeusを使ってみる

Last updated at Posted at 2018-06-12

Typhoeusのコードの例

あまりネットにコーディングの例が載っていなかったので自分で動かしてみました。apiのURLなどのは各自で用意してください。

前回記事

Rubyでhttpリクエストを並列処理

Gemのインストール

コマンドでインストール

gem install typhoeus 

Gemfileでインストール

gem 'typhoeus'

Railsで動かしてみる

railsのrakeファイルを作って動かしてみます。想定はapiにクエリを渡し並列化してhttpリクエストを送る。返ってきたjsonを保持することです。

rails g task typhoeus_task

//返ってくる create  lib/tasks/typhoeus_task.rake

すると、lib/tasks/にtyphoeus_task.rakeファイルができます。rakeとはruby+makeでc言語のmakeコマンドを思い浮かべてもらえばと思います。できたてのファイルは以下のようになっているはず。(#TODOは勝手に書いています)

 namespace :typhoeus_task do
  #TODO ここに内容を書く。                                             
 end          

これを次のように書く。urlやtokenは各自書き換えてください。注意点としては返ってくるjsonがそのままではUnicodeエスケープされている可能性があるので、そのままでは扱えないことがあります。JSON.load()に入れてやるとデコードしてくれます。

 namespace :typhoeus_task do
   task :para_request => :environment do

     search_items = ["a","b","c"]
     items = access_api(search_itmes)
     pp items
   end  

   def access_api(search_items)
     token = "aiueo" 
     url = "https://example.com/search"

     hydra = Typhoeus::Hydra.hydra

     requests = search_items.map do |s_item| 
       body_json = JSON.pretty_generate({"hogequery": s_item}) 

       header = {"Content-Type": "application/json", "X-Auth-Token": token}
       request = Typhoeus::Request.new(url, headers: header, method: :post, body: body_json, followlocation: true)
       hydra.queue(request) #キューに入れていく
       request #これが新しい配列に入っていく
     end

     hydra.run #httpリクエスト実行。結果はrequest.responseに入る

     # responseをjsonにして新しい配列を作る。
     responses = requests.map do |request|
       JSON.load(request.response.body)
     end

     return responses

 end     

そしてターミナルで次のように打つと動くようになる。

rails typhoeus_task:para_request

もしもっと良い書き方があるよって方がいれば、教えていただけると嬉しいです。

3
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
9