如何使用ActionController :: Live以及Resque + Redis(用于聊天应用程序)

Rah*_*ess 7 ruby ruby-on-rails resque redis ruby-on-rails-3

我正在尝试为我的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 %>
Run Code Online (Sandbox Code Playgroud)

..请求即将到来的Publish方法ChatBoxController.

def publish
    $redis.publish("chat_message:1:1", "#{params[:query]}")
    respond_to do |format|
        format.js {render nothing: true}
    end
end
Run Code Online (Sandbox Code Playgroud)

..现在,我有一个以下后台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
Run Code Online (Sandbox Code Playgroud)

我想,以显示Server Sent Events(SSE)连同ActionController::Live在通知Users/show

She*_*yar 13

预REQS:

  • Ruby 2.0.0+
  • Rails 4.0.0+
  • Redis的
  • 美洲狮

初始化:

redis.rbconfig/initializers目录中创建初始化文件,全局化实例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
Run Code Online (Sandbox Code Playgroud)

控制器:

您需要将两种方法添加到您ChatController,pubsub.其作用pub是将聊天事件和消息发布到这些事件redissub订阅这些事件.它应该看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

在你的routes,制作pub a POSTsub a 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
Run Code Online (Sandbox Code Playgroud)

现在,您还需要能够订阅和接收聊天消息.你需要使用EventSource它.使用EventSource,打开SSE的通道,以便您可以接收事件,并使用该数据更新视图.在此示例中,我们只将它们记录到javascript控制台.

代码看起来应该是这样的:

$(document).ready ->
    source = new EventSource('/chat/subscribe')
    source.addEventListener 'chat_event', (e) ->
        console.log(e.data)
Run Code Online (Sandbox Code Playgroud)

注意: 将上面的两个代码块放在您的controllername.coffee文件中,对于此示例,它应该chat.js.coffee在您的app/assets/javascript目录中.您还需要确保将其加载到资产管道中.require它在你的application.js文件中(如果你还没有打电话require tree .).


启用并行请求:

在您的开发环境中,您必须通过将以下两行添加到您的以下来启用并行请求config/environments/development.rb:

config.preload_frameworks = true
config.allow_concurrency = true
Run Code Online (Sandbox Code Playgroud)

现在启动浏览器,浏览/chat并查看魔法.键入消息并单击按钮时,该网页的所有实例都将收到该消息.


这就是你在rails使用ActionController::Live和制作基本聊天应用程序的方法Redis.根据您的要求,最终的代码显然会有很大不同,但这应该可以帮助您入门.

您应该查看更多资源: