1

我一直在阅读 Rails 5(有人知道什么时候发布吗?)将合并对 websockets 的支持,这将使即时消息更容易合并。但我现在正试图为一个相当成熟的应用程序设置一些东西。如果一切顺利,我很快就会拥有相当多的用户,所以它也需要扩展。

我看过 Ryan Bates 的 Private Pub 有点老了,Heroku 的 websocket 示例(我部署在 Heroku 上)、Websocket-rails、actioncable 以及其他一些。大多数看起来都很复杂,所以我想知道我最好的选择是什么,或者 Rails 5 是否会很快推出,我应该等待吗?

谢谢。

4

2 回答 2

2

我偏向于Plezi,它是为扩展(使用 Redis)而构建的,可用于轻松地将 websocket 支持添加到您现有的 web 应用程序中......但再说一遍,我可能对此并不客观。

在 Rails 中运行 Plezi 有两种方法 - 合并应用程序/服务器(使用Iodine HTTP/Websocket 服务器)或使用 Redis 同步两个应用程序。

这两种方式都很容易设置。

要在 Rails 应用程序中使用 Plezi,请在您的应用程序中添加pleziGemfile删除对“瘦”或“puma”或任何其他服务器的任何引用Gemfile- 这应该允许 Iodine 自动接管。比Plezi.app作为中间件放置在您的应用程序中。

您可以通过要求它的文件来包含预制的 Plezi 应用程序,或者 - 甚至更容易 - 您可以将代码写入 Rails 文件之一(可能使用'initializers'、'helpers'或'models'文件夹)。

尝试为聊天室服务器添加以下代码:

require 'plezi'

# do you need automated redis support?
# require 'redis'
# ENV['PL_REDIS_URL'] = "redis://user:password@localhost:6379"

class BroadcastCtrl
    def index
        # we can use the websocket echo page to test our server, 
        # just remember to update the server address in the form.
        redirect_to 'http://www.websocket.org/echo.html'
    end
    def on_message data
        # try replacing the following two lines are with:
        # self.class.broadcast :_send_message, data
        broadcast :_send_message, data
        response << "sent."
    end
    def _send_message data
        response << data
    end
end

route '/broadcast', BroadcastCtrl

这允许我们将一些 Rails 魔法注入到 Plezi 中,并将一些 Plezi 魔法注入到 Rails 中......例如,很容易保存用户的 websocket UUID 并向他们发送更新:

require 'plezi'

# do you need automated redis support?
# require 'redis'
# ENV['PL_REDIS_URL'] = "redis://user:password@localhost:6379"

class UserNotifications
    def on_open
        get_current_user.websocket_uuid = uuid
        get_current_user.save
    end
    def on_close
        # wrap all of the following in a transaction, or scaling might
        # create race conditions and corrupt UUID data
        return unless UsersController.get_current_user.websocket_uuid == uuid
        get_current_user.websocket_uuid = nil 
        get_current_user.save
    end
    def on_message data
         # get data from user and use it somehow
    end
    protected
    def get_current_user
         # # use your authentication system here, maybe:
         # @user ||= UserController.auth_user(cookies[:my_session_id])
    end
    def send_message data
        response << data
    end
end

route '/', UserNotifications

# and in your UserController 

def UserController < ApplicationController
    def update
        # your logic and than send notification:
        data = {}
        UserNotifications.unicast @user.websocket_uuid, :send_message, data.to_json
    end
end
于 2015-09-10T10:26:19.997 回答
0

Rails 5 已经发布。我建议您升级并使用 actioncable。

从长远来看,它应该是最好的选择,因为它将成为 Rails 核心的一部分,并且由 Basecamp 开发、使用和维护。他们将投入足够的精力来确保它稳定、可扩展并被社区接受。

于 2015-10-10T12:10:25.100 回答