在一个简单的Rails5应用程序的单个控制器中,我有两个操作(live
和test
),都使用ActionController::Live
。live
经历了一个循环,并将随机数据写入response.stream.write
,没有任何问题。它起作用了。
然而,在test
中,我使用的是Redis.subscribe。下面是操作代码:
def test
response.headers['Content-Type'] = 'text/event-stream'
redis = Redis.new
redis.subscribe_with_timeout(30, "abc") do |on|
on.message do |event, data|
puts data
response.stream.write data
end
end
rescue IOError
# ignore
ensure
redis.quit
response.stream.close
end
然而,test
方法并不像预期的那样工作。这就是发生的事情:
我启动应用程序并使用curl
访问test
端点。Curl会像预期的那样停止等待数据。然后在redis-cli
中,我向abc
通道发送一条消息。我立即在rails应用程序窗口(puts data
)中看到了我的消息,并且我在curl中看到了以下内容:
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
X-Request-Id: 25df052d-e3f2-4327-9a97-088e702460fa
X-Runtime: 2.709001
Transfer-Encoding: chunked
但是,尽管来自redis-cli
的所有后续消息都打印在rails端,但curl直到超时时间(在subscribe_with_timeout
中为30秒)才会接收到这些消息。
我正在运行Puma,我已经查看并实现了所有关于并发、心跳线程和更多的Stackoverflow答案,但没有运气。
发布于 2019-06-17 05:06:02
在深入研究之后,您发现需要在输出到response.stream.write
的任何内容的末尾添加一个新的"\n"
行,才能使其从缓冲区中取出。
https://stackoverflow.com/questions/56619324
复制相似问题