Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ruby - async requests using sinatra streaming API

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...