我正在尝试为我的 Rails 应用程序构建聊天功能。为此,我正在使用 ActionController::Live
、Puma
、Resque
、Redis
。所以基本上在这种情况下,redis subscribe
方法使用 resque
在后台运行。
到目前为止,我所做的是每当用户在下面的表单字段(即聊天框)中输入文本时
<%= form_tag chat_box_publish_path, method: :get do %>
<%= text_field_tag :query, params[:query], class: "form-control", id: "chatSearchBox",
placeholder: 'Search' %>
<% end %>
..请求到达 ChatBoxController
中的 Publish
方法。
def publish
$redis.publish("chat_message:1:1", "#{params[:query]}")
respond_to do |format|
format.js {render nothing: true}
end
end
..现在我有一个低于背景的 Resque
作业,使用下面的代码运行以用于测试目的。因此,每当发布聊天消息时,它都会打印 data
,这很好。但是如何将 ActionController::Live
功能添加到后台作业?或者我该如何着手实现?此设计需要帮助。
class ChatBoxInitiator
@queue = :chat_box_initiator
private
def self.perform
$redis.subscribe('chat_message:1:1') do |on|
on.message do |event, data|
puts "====#{data}"
return data
end
end
end
end
我想在 Users/show
页面中显示 Server Sent Events(SSE)
以及 ActionController::Live
通知
最佳答案
先决条件:
- ruby 2.0.0+
- rails 4.0.0+
- Redis
- 彪马
初始化器:
在config/initializers
目录下创建一个redis.rb
初始化文件,全局化一个redis
实例。设置一个 heartbeat
线程也是个好主意(5 秒到 5 分钟都可以,具体取决于您的要求):
$redis = Redis.new
heartbeat_thread = Thread.new do
while true
$redis.publish("heartbeat","thump")
sleep 15.seconds
end
end
at_exit do
heartbeat_thread.kill
$redis.quit
end
Controller :
您需要向您的ChatController
添加两个方法,pub
和sub
。 pub
的作用是将聊天事件和消息发布到redis
,sub
订阅这些事件。它应该看起来像这样:
class ChatController < ApplicationController
include ActionController::Live
skip_before_filter :verify_authenticity_token
def index
end
def pub
$redis.publish 'chat_event', params[:chat_data].to_json
render json: {}, status: 200
end
def sub
response.headers["Content-Type"] = "text/event-stream"
redis = Redis.new
redis.subscribe(['chat_event', 'heartbeat']) do |on|
on.message do |event, data|
response.stream.write "event: #{event}\ndata: #{data}\n\n"
end
end
rescue IOError
logger.info "Stream Closed"
ensure
redis.quit
response.stream.close
end
end
在您的路由
中,将pub 设为POST
和sub GET
,并将路径与 /chat/publish
和 /chat/subscribe
相匹配。
CoffeeScript /Javascript:
假设聊天应用程序的实际网页位于 /chat
,您需要编写一些 Javascript 来实际发送和接收聊天消息。
为了便于理解,我们假设您的网页只有一个文本框和一个按钮。点击按钮应该将文本框的内容发布到聊天流,我们可以使用 AJAX 来做到这一点:
$('button#send').click (e) ->
e.preventDefault()
$.ajax '/chat/publish',
type: 'POST'
data:
chat_data: {
message: $("input#message").val()
timestamp: $.now()
error: (jqXHR, textStatus, errorThrown) ->
console.log "Failed: " + textStatus
success: (data, textStatus, jqXHR) ->
console.log "Success: " + textStatus
现在,您还需要能够订阅和接收聊天消息。为此,您需要使用 EventSource
。使用 EventSource,为 SSE 打开一个 channel ,以便您可以接收事件,并使用该数据更新 View 。在这个例子中,我们只会将它们记录到 javascript 控制台。
代码应该是这样的:
$(document).ready ->
source = new EventSource('/chat/subscribe')
source.addEventListener 'chat_event', (e) ->
console.log(e.data)
注意: 将上面的两个代码块放在您的 controllername.coffee
文件中,对于此示例,它应该是 chat.js.coffee
在您的 app/assets/javascript
目录中。您还需要确保它正在加载到 Assets 管道中。 require
在你的 application.js
文件中(如果你还没有调用 require tree .
)。
启用并行请求:
在您的开发环境中,您必须通过将这两行添加到您的 config/environments/development.rb
来启用并行请求:
config.preload_frameworks = true
config.allow_concurrency = true
现在启动您的浏览器,浏览至 /chat
并查看魔术。当您键入一条消息并单击该按钮时,该网页的所有实例都会收到该消息。
这就是您使用 ActionController::Live
和 Redis
在 rails
中制作基本聊天应用程序的方法。根据您的要求,最终代码显然会有很大不同,但这应该可以帮助您入门。
您应该查看更多资源:
- 温柔的做爱 - Is it Live?
- Railscasts - #401 - ActionController::Live
- SitePoint - Mini Chat with Rails and SSEs
- Github - mohanraj-ramanujam / live-stream
- Thoughtbot - Chat Example using SSEs
关于ruby-on-rails - 如何使用 ActionController::Live 以及 Resque + Redis(用于聊天应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29150274/