首页 > 其他 > 详细

eventmachine 到底是干什么的呢?

时间:2014-02-16 20:43:09      阅读:530      评论:0      收藏:0      [点我收藏+]


因为公司项目要使用rabbitmq,于是查找到amqp这个协议,最后又看到了 passenger 集成 amqp的例子-----ubyonrails23_passenger_amqp_gem_example。其中有一段ruby代码很费解。

if defined?(PhusionPassenger) # otherwise it breaks rake commands if you put this in an initializer
  PhusionPassenger.on_event(:starting_worker_process) do |forked|
    require ‘eventmachine‘
    require ‘amqp‘

    if forked
      Rails.logger.info "[AMQP] Initializing amqp..."
      amqp_thread = Thread.new {
        failure_handler = lambda {
          Rails.logger.fatal Terminal.red("[AMQP] [FATAL] Could not connect to AMQP broker")
        }
        AMQP.start(:on_tcp_connection_failure => failure_handler)
      }
      amqp_thread.abort_on_exception = true
      sleep(0.15)

      EventMachine.next_tick do
        AMQP.channel ||= AMQP::Channel.new(AMQP.connection)

        queue_name = "amqpgem.examples.rails23.passenger.index"
        AMQP.channel.queue(queue_name, :durable => true).subscribe do |message|
          Rails.logger.info Terminal.green("[AMQP] Received \"#{message}\" from #{queue_name}")
        end

      end
    end
  end
end

可以看出大概就是连接rabbitmq后发消息和接收处理消息相关的代码,但是读起来却着实让人难以猜测其中的意思。

一番查找后,才知道最主要的是eventmachine这个东西不理解。

于是查看教程文档:

http://wonderflow.info/wp-content/uploads/2013/07/EventMachine%E5%85%A5%E9%97%A8.pdf

看完后联想到之前有同事分享的node.js异步机制,感觉有几分类似。


首先就是reactor模式

bubuko.com,布布扣


按照本人理解,keyboard有pressdown  pressup等操作, 经由reactor分发给对应的事件进行处理,如果处理事件的代码较长,则通过threadpool中的线程进行处理。和java中的awt编程是类似的,程序员不需要关注代码的执行先后,只需要在对应的事件上添加上处理逻辑就可以了。这种编程模型实际上是一种异步编程模型。

eventmachine就是干这个活的,通过对注册事件来更好的处理问题。具体使用方式见:http://wonderflow.info/wp-content/uploads/2013/07/EventMachine%E5%85%A5%E9%97%A8.pdf


eventmachine 到底是干什么的呢?

原文:http://blog.csdn.net/codelifeofme/article/details/19260065

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!