eventmachine 到底是干什么的呢?


因为公司项目要使用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模式



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

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值