【问题标题】:How do you stream from a database table using ActionController::Live?如何使用 ActionController::Live 从数据库表中流式传输?
【发布时间】:2014-02-10 01:30:29
【问题描述】:

设置:在我的环境中,Java 程序连续写入名为readings 的PostgreSQL 数据库表,例如每秒一次。

我正在构建一个连接到同一个数据库并显示这些读数的 rails 应用程序。这是静态显示读数的图片。

问题:要查看新读数,我必须刷新。

问题:如何使用 ActionController::Live 使此页面显示新记录?我想我需要轮询数据库以获取新记录并更新 @readings 变量,但我不知道如何。

这里是readings_controller.rb的开头。

class ReadingsController < ApplicationController                                    
  include ActionController::Live                                                    

  before_action :set_reading, only: [:show, :edit, :update, :destroy]               

  # GET /readings                                                                   
  # GET /readings.json                                                              
  def index                                                                         
    @search = Reading.search(params[:q])                                            
    @readings = @search.result.order('time DESC').paginate(:page => params[:page])
  end 

【问题讨论】:

    标签: javascript ruby-on-rails ruby-on-rails-4 real-time actioncontroller


    【解决方案1】:

    ActionController::Live 本身就是一头野兽

    您不能像普通控制器/动作一样使用它 - 它必须与 SSE'sweb sockets 一起使用以提供连接。我不相信你可以在没有永久连接的情况下让它工作

    Excellent resource


    ActionController::Live

    我看到这个工作的方式是:

    • 你通过控制器/动作连接
    • 保持连接(前端使用 Web 套接字/SSE)
    • 任何更新都会发布到连接(通过 ActionController::Live)

    我会这样做:


    JS

    创建一个 SSE 监听器:

    #app/assets/javascripts/special_javascript.js
    jQuery(document).ready(function() {
      setTimeout(function() {
        var source = new EventSource('/your/action');
        source.addEventListener('refresh', function(e) {
          window.location.reload();
        });
      }, 1);
    });
    

    控制器

    class ReadingsController < ActionController::Base
      include ActionController::Live
    
      def create
        response.stream.write "Updated" #-> send updated db stuff
        response.stream.close
      end
    end
    

    这将允许您监视数据库中的更改。如果您希望使用新的数据库信息更新页面,我们将不得不调查您如何传递数据

    实际上我们强烈推荐一个名为Pusher 的服务来为您处理这个问题

    【讨论】:

    • 这是一个很好的尝试。虽然,这不是我想要的。我喜欢 Pusher 的想法。不过,理想的解决方案不需要互联网连接。
    猜你喜欢
    • 2017-01-08
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 2023-01-30
    • 2022-11-03
    • 2019-10-29
    相关资源
    最近更新 更多