0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Net::HTTPのtimeoutを設定する

Posted at

環境

Ubuntu20.4
Ruby2.6

内容

下記のコードでAPIでデータを取得しようとしたところ、サーバーの処理が重くタイムアウトになってしまいました。タイムアウトになると例外に飛んでしまいます。ちなみにタイムアウトのデフォルトは2分です。正確にいえば、open_timeoutが60秒、read_timeoutが60秒なので合計2分ということになります。

get_responseメソッドを使うと、内部でデフォルトで保持しているタイムアウトの値を変更できないためコードを書き換えました。

sample1.rb
require 'net/http'

url = "https://www.sample.com"
respon = Net::HTTP.get_response(URI.parse(url))
result = JSON.parse(respon.body)

書き換えたコードが下記です。このように書き換えることでタイムアウトの値をカスタマイズできるようになります。サーバーへの接続の段階では重たくなることがない場合はopen_timeoutまで延ばす必要はありません。

sample2.rb
require 'net/http'

url = "https://www.sample.com"
uri = URI.parse(url)

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
http.open_timeout = 60 * 10
http.read_timeout = 60 * 10

response = http.start { http.get(uri) }
result = JSON.parse(response.body)

ググっていると同じようなことで悩んでいる例が割とあるようでしたので、参考になればと思い記事にしてみました。

参考記事

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?