httpリクエスト発行

rubyで簡単にhttpリクエストを発行する方法が分かったので、メモ。

require 'open-uri'
open("http://localhost:5555/sample/index.html"){|f| puts f.read }

こんな感じ。結果としてのHTMLが出力されます。ただし、文字化けが起こったので、次のように文字化け対策をした。

require 'open-uri'
require 'nkf'
open("http://localhost:5555/sample/index.html"){|f| puts NKF.nkf('-s', f.read) }

ここまでは余談で、一番やりたかったのは、httpリクエストの大量発行。スレッドを使って次のようにしました。

require 'open-uri'

threads = []

100.times do
  threads << Thread.new do
    begin
      open("http://localhost:5555/sample/index.html"){|f| puts f.status.join }
    rescue => e
      puts "例外発生! #{e}"
    end
  end
end

threads.each{|t| t.join}

Tomcatに展開しているアプリケーションでデータソースを使っている場合、許容範囲を超えたらどうなるのかをこのプログラムを使って実験してみました。データソース設定を一時的に次のように変更します。

maxActive="1"
maxIdle="1"
maxWait="2000"

で、実験結果ですが、定期的に例外が発生し、「500 Internal Server Error」が出力されました。