我使用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
解决方法
回答我自己的问题:
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