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