使用sinatra流API的异步请求

时间:2013-02-21 02:02:50

标签: ruby sinatra eventmachine

我使用async_sinatra gem来实现异步路由,但我遇到了一个帖子,说明为了这个目的,可以使用Sinatra的流API代替async_sinatra。可以使用流媒体实现与以下相同的功能吗?

require 'em-hiredis'
require 'sinatra/async'

class App < Sinatra::Base
  register Sinatra::Async

  def redis
    @redis ||= EM::Hiredis.connect
  end

  aget '/' do
    redis.blpop('abcdef', 15).
      callback {|x| body "x=#{x}"}.
      errback {|e| body "e=#{e}"}
  end

  run! if app_file == $0
end

1 个答案:

答案 0 :(得分:3)

回答我自己的问题:

require 'em-hiredis'
require 'sinatra/base'

class App < Sinatra::Base
  def redis
    @redis ||= EM::Hiredis.connect
  end

  get '/' do
    stream :keep_open do |out|
      redis.blpop('abcdef', 15).callback do |x|
        out << "x=#{x}"
        out.close
      end.errback do |e|
        out << "e=#{e}"
        out.close
      end
    end
  end

  run! if app_file == $0
end