【问题标题】:ActionController::Live - SSE in RailsActionController::Live - Rails 中的 SSE
【发布时间】:2015-01-28 14:03:30
【问题描述】:

我希望在不重新加载服务器的情况下将数据库中的更改反映在页面上。

控制器

class ProductController < ApplicationController
  include ActionController::Live

  def index
    @product = Product.available
    response.headers['Content-Type'] = 'text/event-stream'
    sse = SSE.new(response.stream)
    sse.write @product
  ensure
    sse.close
  end
end 

查看

<p><%= @product[:price] %></p>

我正在使用彪马。

当我在数据库中更新产品时,更改不会反映在网页上。

我错过了什么?

【问题讨论】:

    标签: ruby-on-rails multithreading concurrency server-sent-events puma


    【解决方案1】:

    Rails 无法实时更新视图。它提供 html,然后由一些 JavaScript 来监听流并处理事件。

    我创建了一个 gem,淋浴,它可以为你处理所有这些。 https://github.com/kpheasey/shower

    使用 Shower,解决方案是这样的。

    首先您需要发布更新事件,这可以通过 Product 模型上的 after_update 回调来完成。

    class Product < ActiveRecord::Base
        after_update :publish_event
    
        def publish_event
            Shower::Stream.publish('product.update', self)
        end
    end
    

    然后你需要一些 javascript 来监听事件流并对其采取行动。

    $ ->
        stream = new Shower('/stream', ['product.update'])
    
        stream.addEventListener('product.update', (event) ->
          product = JSON.parse(event.data)
          $('p').html(product.price)
        )
    

    【讨论】:

    • Redis 目前不在我的堆栈中。我必须进行任何特殊配置才能使其正常工作吗? @KPheasey
    • 你只需要在本地系统上安装redis即可。通过 Mac 上的 Homebrew 或通过 linux 系统上的软件包安装非常容易,digitalocean.com/community/tutorials/…
    • 似乎 Shower 创建了一条路由 ---get '/stream', to: 'shower/stream#index'--- 流是流式传输到 /stream 的吗?如果是这样,在访问该页面时,Rails 会抱怨:“无法修改冻结的哈希”@KPheasey
    猜你喜欢
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    相关资源
    最近更新 更多