当用户中止连接时执行某些操作(Sinatra + Thin)

发布于 2024-12-19 22:23:50 字数 580 浏览 4 评论 0原文

我正在编写一个有时需要非常长时间运行的数据库请求的应用程序。如果客户端重新加载或关闭页面以处理数据库请求,我想执行一些代码。

我本来希望 Rack 能够与这种事情挂钩,但显然从我所看到的来看,这比 Rack 更深层次。

到目前为止,我能找到的唯一挂钩是通过对 Thin Connection 类中的取消绑定函数进行猴子修补来进入 Thin 本身:

module Thin
  class Connection < EventMachine::Connection

    def unbind

      # DO something here

      @request.async_close.succeed if @request.async_close
      @response.body.fail if @response.body.respond_to?(:fail)
      @backend.connection_finished(self)
    end
  end
end

这会覆盖 Thin 的取消绑定函数,并让我挂钩由 EventMachine 调用的断开连接。

有更好的办法吗?

I'm writing an app that sometimes requires very long-running DB requests. I'd like to execute some code if the client reloads or closes the page to do things with the DB requests.

I was hoping that Rack would have hooks into this sorta thing, but apparently from what I've seen this is a level deeper than Rack goes.

So far, the only hook I can find is into thin itself, by monkey-patching the unbind function in the thin Connection class:

module Thin
  class Connection < EventMachine::Connection

    def unbind

      # DO something here

      @request.async_close.succeed if @request.async_close
      @response.body.fail if @response.body.respond_to?(:fail)
      @backend.connection_finished(self)
    end
  end
end

This overrides Thin's unbind function and lets me hook into the disconnect called by EventMachine.

Is there a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倒带 2024-12-26 22:23:50

经过一番挖掘,我发现 Thin 提供了一种替换“后端”的机制,或者服务器如何连接到客户端的机制。我正在使用它,结合机架环境中的值来处理特定的请求实例,并知道我是否需要终止查询:

class Backend < Thin::Backends::TcpServer

  def initialize(host, port, options={})
    super(host, port)
  end

  def connection_finished(connection)
    super(connection)

    if connection.request.env["query_killer"]
      connection.request.env["query_killer"].kill
    end

  end

end

这可以通过命令行参数包含在 Thin 中:

thin start  -r 'my_module/backend' --backend MyModule::Backend

After some digging, I've found that Thin provides a mechanism for replacing the 'backend', or how the server connects to the client. I'm using that, combined with values in the rack env to deal with specific request instances and know if I need to kill a query or not:

class Backend < Thin::Backends::TcpServer

  def initialize(host, port, options={})
    super(host, port)
  end

  def connection_finished(connection)
    super(connection)

    if connection.request.env["query_killer"]
      connection.request.env["query_killer"].kill
    end

  end

end

This can be included into thin via command-line arguments:

thin start  -r 'my_module/backend' --backend MyModule::Backend
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文