加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

异步方法使用Ruby调用Ajax

发布时间:2020-12-17 03:13:40 所属栏目:百科 来源:网络整理
导读:我正在使用XMPP,我有一个消息回调,它会在发送每条消息时被激活.我的目标是将消息到达的数据发送到回调中的API,并根据响应使用XMPP客户端发回一些内容. 用户类型消息(浏览器聊天客户端) 消息通过XMPP到达服务器 消息被发送到API 收到回复 响应被发送回聊天客
我正在使用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这样的Javascript来激活请求,当响应可用时发送数据.我怎么能在Ruby中实现它?

我查看了delayed_job和backgroundrb,它们看起来像火灾和忘记操作的工具.我需要一些能够以异步方式使用响应激活回调的东西.

我真的很感激如何实现我想要的异步行为的一些帮助.我也熟悉像RabbitMQ这样的消息队列,我觉得这会增加很多复杂性.

解决方法

你看过 girl_friday吗?从它的维基 –

girl_friday is a Ruby library for performing asynchronous tasks. Often times you don’t want to block a web response by performing some task,like sending an email,so you can just use this gem to perform it in the background. It works with any Ruby application,including Rails 3 applications.

Why not use any of the zillions of other async solutions (Resque,dj,etc)? Because girl_friday is easier and more efficient than those solutions: girl_friday runs in your Rails process and uses the actor pattern for safe concurrency. Because it runs in the same process,you don’t have to monitor a separate set of processes,deploy a separate codebase,waste hundreds of extra MB in RAM for those processes,etc. See my intro to Actors in Ruby for more detail.

You do need to write thread-safe code. This is not hard to do: the actor pattern means that you get a message and process that message. There is no shared data which requires locks and could lead to deadlock in your application code. Because girl_friday does use Threads under the covers,you need to ensure that your Ruby environment can execute Threads efficiently. JRuby,Rubinius 1.2 and Ruby 1.9.2 should be sufficient for most applications. I do not support Ruby 1.8 because of its poor threading support.

我想这就是你要找的东西.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读