使用 sinatra 流 API 的异步请求
问题描述:
我使用 async_sinatra
gem 来实现异步路由,但我在某处看到一篇帖子说 Sinatra 的流 API 可以用来代替 async_sinatra
用于此目的.是否可以使用流式传输实现与以下相同的功能?
I use async_sinatra
gem to implement asynchronous routes, but I came across a post somewhere that said that Sinatra's streaming API can be used instead of async_sinatra
for this purpose. Can the same functionality as below be implemented using streaming?
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