当用户中止连接时执行某些操作(Sinatra + Thin)
我正在编写一个有时需要非常长时间运行的数据库请求的应用程序。如果客户端重新加载或关闭页面以处理数据库请求,我想执行一些代码。
我本来希望 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过一番挖掘,我发现 Thin 提供了一种替换“后端”的机制,或者服务器如何连接到客户端的机制。我正在使用它,结合机架环境中的值来处理特定的请求实例,并知道我是否需要终止查询:
这可以通过命令行参数包含在 Thin 中:
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:
This can be included into thin via command-line arguments: