async requests using sinatra streaming API

﹥>﹥吖頭↗ 提交于 2019-11-28 08:36:11

问题


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

回答1:


to answer my own question:

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


来源:https://stackoverflow.com/questions/14993386/async-requests-using-sinatra-streaming-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!