にたまごほうれん草アーカイブ

はてなダイアリーで書いてた「にたまごほうれん草」という日記のアーカイブです。現在は「にたまごほうれん草ブログ」を運営中です。

ローカルに立てたプロキシサーバに負荷をかけてみるテストスクリプト

一回目だけ接続先のサイトさんに我慢いただく。

#! /usr/bin/ruby -w
require 'net/http'

$proxy_addr = 'localhost'
$proxy_port = 9080

th = []
100.times do |i|
  th[i] = Thread.start {
    Thread.current["count"] = i
    host = 'www.trynt.com'
    path = "/body-mass-index-api/v1/?h=1.8&w=#{30+i}&t=metric"
    Net::HTTP::Proxy($proxy_addr, $proxy_port).start(host) {|http|
      resp = http.get(path)
      File.open("result/#{i}", "wb") {|file|
        puts "request:#{i} = #{resp.code}"
        case resp
        when Net::HTTPSuccess then
          file.write(resp.body)
        else
          file.write(resp.message)
        end
      }
    }
  }
end
th.each {|t| t.join; puts 'thread count is ' + t["count"].to_s }

なんか走り出したスレッドをちゃんと同期して受ける方法がすぐにわからなかった。いつか修正しよう。

追記

修正しました。前はjoinのやり方がまずかったらしい。