使用 Ruby 进行异步方法调用,就像使用 Ajax 一样
我正在使用 XMPP,并且有一个消息回调,在发送每条消息时都会激活该消息回调。我的目标是将消息到达的数据发送到回调中的 API,并根据响应使用 XMPP 客户端发回一些内容。
- 用户类型消息(浏览器聊天客户端)
- 消息通过 XMPP 到达服务器
- 消息发送到 API
- 收到响应
- 响应被发送回聊天客户端。
我的代码如下,
admin_muc_client.activate_message_callbacks do |m|
sender = m.from.resource
room_slug = m.from.node
message = m.body
r = HTTParty.get('http://example.com/api/v1/query?msg=message')
Rails.logger.debug(r.inspect)
admin_muc_client.send_message("Message #{r.body}") if m.from.resource != 'admin'
end
我在这里担心的是,由于回调是事件化的,并且对 API 的请求将是阻塞调用,这可能成为整个应用程序的瓶颈。 我更喜欢使用 AJAX for Javascript 之类的东西,它会触发请求,并在响应可用时发送数据。我如何在 Ruby 中实现它?
我查看了delayed_job 和backgroundrb,它们看起来像是“即发即忘”操作的工具。我需要一些能够以异步方式与响应激活回调的东西。
我真的非常感谢有关如何实现我想要的异步行为的一些帮助。我也熟悉像 RabbitMQ 这样的消息队列,我认为这会增加显着的复杂性。
I am working with XMPP and I have a message callback which is activated on the event of every message being sent. My aim is to send the data arriving by the message to an API within the callback and based on the response send something back using the XMPP client.
- User type message (Browser Chat Client)
- Message arrives to the server via XMPP
- Message is sent to the API
- Response is received
- Response is sent back to the chat client.
My code for this is as follows
admin_muc_client.activate_message_callbacks do |m|
sender = m.from.resource
room_slug = m.from.node
message = m.body
r = HTTParty.get('http://example.com/api/v1/query?msg=message')
Rails.logger.debug(r.inspect)
admin_muc_client.send_message("Message #{r.body}") if m.from.resource != 'admin'
end
My concern here is that since the callback is evented and the request to the API would be a blocking call this could become a bottleneck for the entire application.
I would prefer to use something like AJAX for Javascript which would fire the request and when the response is available send data. How could I implement that in Ruby?
I have looked at delayed_job and backgroundrb which look like tools for fire and forget operations. I would need something that activates a callback in an asynchronous manner with the response.
I would really really appreciate some help on how to achieve the asynchronous behavior that i want. I am also familiar with message queues like RabbitMQ which I feel would be addition of significant complexity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你看过girl_friday吗?来自它的维基 -
我想这就是您正在寻找的。
Did you look at girl_friday? From it's wiki -
I think this is what you are looking for.