Tech Tips

  1. プログラミング
  2. 334 view

[StreamingAPI][Ruby]ストリーミングREST APIをrubyで作ってみる

Contents

概要

Rubyのrack-streamライブラリで
Streaming APIを作成してみる。

環境

OS

Linux www4322gi 3.2.0-64-generic #97-Ubuntu SMP Wed Jun 4 22:04:21 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

Ruby

rbenv(ruby version : ruby 1.9.3p547 (2014-05-14 revision 45962) [x86_64-linux])

コード

基本的にはrack-streamのgithubにのっているソースコードをそのまま動かしただけの内容。

Gemfile

rack-streamとWebサーバとしてthinを利用する。
source 'https://rubygems.org'

gem 'thin'
gem 'rack-stream'

config.ru

#  bundle exec thin start -R config.ru -p 9292
# config.ru
# run with `thin start -p 9292`
require 'rack/stream'

class App
  include Rack::Stream::DSL

  stream do
    after_open do
      count = 0
      @timer = EM.add_periodic_timer(1) do
        if count != 3
          chunk "chunky #{count}\n"
          count += 1
        else
          # Connection isn't closed until #close is called.
          # Useful if you're building a firehose API
          close
        end
      end
    end

    before_close do
      @timer.cancel
      chunk "monkey!\n"
    end

    [200, {'Content-Type' => 'text/plain'}, []]
  end
end

app = Rack::Builder.app do
  use Rack::Stream
  run App.new
end

run app

実行結果

# Server
$ bundle exec thin start -R config.ru -p 9292
Thin web server (v1.6.2 codename Doc Brown)
Maximum connections set to 1024
Listening on 0.0.0.0:9292, CTRL+C to stop

# Client
curl http://localhost:9292
chunky 0
chunky 1
chunky 2
monkey!

プログラミングの最近記事

  1. PlatformIO IDE for VSCode を使用して VSCode で Ardu…

  2. ROS Docker イメージで発生した GPG error の解消方法

  3. Streamlit で訪れた国を色づけした世界地図を作成できるアプリケーションを作成してみ…

  4. M5Stack Core2 for AWS – ESP32 IoT開発キットで…

  5. D3.js v7 で点・線・テキスト・ツールチップ・ズームを設定する方法

関連記事

PAGE TOP